summaryrefslogtreecommitdiff
path: root/l10ntools/layout/tralay.cxx
blob: c113cb46730515fbb9fd7aecd4735883d4ff5c50 (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
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/



#include <com/sun/star/xml/sax/SAXException.hpp>
#include <l10ntools/vosapp.hxx>

#include <osl/file.hxx>

#include "export.hxx"
#include "layoutparse.hxx"
#include "helpmerge.hxx"
#include "xmlparse.hxx"

// Convert a rtl::OUString to a byte string.
#define OUSTRING_CSTR( str ) \
    rtl::OUStringToOString( str, RTL_TEXTENCODING_UTF8 ).getStr()

#define STRING( str ) String( str, RTL_TEXTENCODING_UTF8 )
#define BSTRING( str ) ByteString( str, RTL_TEXTENCODING_UTF8 )

using ::rtl::OUString;

using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;


class TranslateLayout : public Application
{
    ByteString mGid1;
    ByteString mLanguage;
    ByteString mLocalize;
    ByteString mOutput;
    ByteString mProject;
    ByteString mRoot;
    bool mMergeMode;
    std::vector< ByteString > mLanguages;
    std::list< ByteString > mFiles;

public:
    TranslateLayout();
    virtual ~TranslateLayout();
    ByteString GetCommandLineParam( int i );
    ByteString GetOptionArgument( int const i );
    void ExceptionalMain();
    void Main();
    void Merge();
    void MergeLanguage( ByteString const& language );
    void ParseCommandLine();
    void CreateSDF();

    using Application::GetCommandLineParam;
};

static void usage()
{
    fprintf( stderr, "Usage: tralay [OPTION]... XML-FILE\n" );
    fprintf( stderr, "\nOptions:\n" );
    fprintf( stderr, "  -h,--help                  show this help\n" );
    fprintf( stderr, "  -l,--language=LANG         process this language\n" );
    fprintf( stderr, "  -m,--merge=DATABASE.SDF    translation database\n" );
    fprintf( stderr, "\nExamples:\n" );
    fprintf( stderr, "  tralay -l en-US -o localize.sdf zoom.xml   # Extract\n" );
    fprintf( stderr, "  tralay -m localize.sdf -l de -l nl -o out zoom.xml  # Merge/translate\n" );
    exit( 2 );
}

static ByteString ConvertSystemPath( const ByteString& rPath )
{
    if( rPath.CompareTo( ".", 1 ) == 0 )
    {
        OUString sPath( rPath.GetBuffer(), rPath.Len(), RTL_TEXTENCODING_UTF8 );

        ::rtl::OUString curDirPth, sURL;
        osl_getProcessWorkingDir( &curDirPth.pData );

        ::osl::FileBase::getAbsoluteFileURL( curDirPth, sPath, sURL );
        ::osl::FileBase::getSystemPathFromFileURL( sURL, sPath );

        return ByteString( rtl::OUStringToOString( sPath, RTL_TEXTENCODING_UTF8 ) );
    }
    else
    {
        return rPath;
    }
}

ByteString TranslateLayout::GetCommandLineParam( int i )
{
    return ByteString( OUSTRING_CSTR( Application::GetCommandLineParam( sal::static_int_cast< sal_uInt16 >( i ) ) ) );
}

ByteString TranslateLayout::GetOptionArgument( int const i )
{
    if ( i >= GetCommandLineParamCount() )
        usage();
    ByteString arg = GetCommandLineParam( i );
    if ( !arg.CompareTo( "-", 1 ) )
    {
        fprintf( stderr, "Option needs an argument: %s, found: %s\n",
                 GetCommandLineParam( i - 1 ).GetBuffer(),
                 arg.GetBuffer() );
        usage();
    }
    return arg;
 }

void TranslateLayout::ParseCommandLine()
{
    for ( int i = 0; i < GetCommandLineParamCount(); i++ )
    {
        ByteString aParam = GetCommandLineParam( i );
        if ( aParam.Equals( "-h" ) || aParam.Equals( "--help" ) )
            usage();
        else if ( aParam.Equals( "-l" ) || aParam.Equals( "--language" ) )
            mLanguages.push_back ( GetOptionArgument( ++i ) );
        else if ( aParam.Equals( "-m" ) || aParam.Equals( "--merge" ) )
        {
            mMergeMode = true;
            mLocalize = GetOptionArgument( ++i );
        }
        else if ( aParam.Equals( "-o" ) || aParam.Equals( "--output" ) )
            mOutput = ConvertSystemPath( GetOptionArgument( ++i ) );
        else if ( !aParam.CompareTo( "-", 1 ) )
        {
            fprintf( stderr, "error: No such option: %s\n", aParam.GetBuffer() );
            usage();
        }
        else
            mFiles.push_back( ConvertSystemPath( aParam ) );
    }
    if ( !mFiles.size() )
    {
        fprintf( stderr, "error: No XML-FILE found\n" );
        usage();
    }
}

static XMLAttribute*
findAttribute( XMLAttributeList* lst, String const& name )
{
    for ( sal_uLong i = 0; i < lst->Count(); i++ )
        if ( lst->GetObject( i )->Equals( name ) )
            return lst->GetObject( i );
    return 0;
}

static XMLAttribute*
translateAttribute( XMLAttributeList* lst,
                    String const& name, String const& translation )
{
    if ( XMLAttribute* a = findAttribute( lst, name ) )
        return lst->Replace ( new XMLAttribute( name.Copy( 1 ), translation ), a );
    return 0;
}

static void
translateElement( XMLElement* element, ByteString const& lang,
                  ResData* resData, MergeDataFile& mergeData )
{
    XMLAttributeList* attributes = element->GetAttributeList();
    std::vector<XMLAttribute*> interesting( interestingAttributes( attributes ) );


    if( !interesting.empty() )
    {
        std::vector<XMLAttribute*>::iterator i( interesting.begin() );
        ByteString id = BSTRING( (*i++)->GetValue() );
        for ( ; i != interesting.end(); ++i )
        {
            ByteString attributeId = id;
            attributeId += BSTRING ( **i );
            resData->sGId = attributeId;
            resData->sId = element->GetOldref();

            if ( PFormEntrys* entry = mergeData.GetPFormEntrys( resData ) )
            {
                ByteString translation;
                entry->GetText( translation, STRING_TYP_TEXT, lang, true );
    //            ByteString original = removeContent( element );
                if ( !translation.Len() )
#if 0
                    translation = original;
#else
                    translation = BSTRING( ( *i )->GetValue() );
#endif
                delete translateAttribute( attributes, **i , STRING( translation ) );
            }
        }
    }
}

static bool is_dir( ByteString const& name )
{
    DirectoryItem aItem;
    OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 );
    FileBase::getFileURLFromSystemPath( sFileURL, sFileURL );
    if( DirectoryItem::get( sFileURL, aItem ) == FileBase::E_None )
    {
        FileStatus aStatus(FileStatusMask_Type);
        if( aItem.getFileStatus( aStatus ) == FileBase::E_None )
        {
            if( aStatus.getFileType() == FileStatus::Directory )
                return true;
        }
    }
    return false;
}

static void make_directory( ByteString const& name )
{
    OUString sFileURL( name.GetBuffer(), name.Len(), RTL_TEXTENCODING_UTF8 );
    FileBase::getFileURLFromSystemPath( sFileURL, sFileURL );
    Directory::create( sFileURL );
}

static void insertMarker( XMLParentNode *p, ByteString const& file )
{
    if ( XMLChildNodeList* lst = p->GetChildList() )
        if ( lst->Count() )
        {
            sal_uLong i = 1;
            // Skip newline, if possible.
            if ( lst->Count() > 1
                 && lst->GetObject( 2 )->GetNodeType() == XML_NODE_TYPE_DEFAULT )
                i++;
            OUString marker = OUString::createFromAscii( "\n    NOTE: This file has been generated automagically by transex3/layout/tralay,\n          from source template: " )
                + STRING( file )
                + OUString::createFromAscii( ".\n          Do not edit, changes will be lost.\n" );
            lst->Insert( new XMLComment( marker, 0 ), i );
        }
}

void TranslateLayout::MergeLanguage( ByteString const& language )
{
    ByteString xmlFile = mFiles.front();

    MergeDataFile mergeData( mLocalize, xmlFile,
                             sal_False, RTL_TEXTENCODING_MS_1252 );

    DirEntry aFile( xmlFile );
    SimpleXMLParser aParser;
    LayoutXMLFile* layoutXml = new LayoutXMLFile( mMergeMode );
    if ( !aParser.Execute( aFile.GetFull() , STRING( xmlFile ), layoutXml ) )
    {
        fprintf(stderr, "error: parsing: %s\n", xmlFile.GetBuffer() );
        return;
    }

    layoutXml->Extract();
    insertMarker( layoutXml, xmlFile );

    ResData resData( "", "", "" );
    resData.sResTyp = mProject; /* mGid1 ?? */
    resData.sFilename = xmlFile;

    XMLHashMap* xmlStrings = layoutXml->GetStrings();
    for ( XMLHashMap::iterator i = xmlStrings->begin(); i != xmlStrings->end();
          ++i )
    {
        if ( LangHashMap* languageMap = i->second )
            if ( XMLElement* element = ( *languageMap )[ "en-US" ] )
                translateElement( element, language, &resData, mergeData );
    }

#ifndef WNT
    ByteString outFile = "/dev/stdout";
#else
    ByteString outFile = "\\\\.\\CON";
#endif
    if ( mOutput.Len() )
    {
        outFile = mOutput;
        if ( is_dir( outFile ) )
        {
            ByteString outDir = mOutput;
            outDir.Append( "/" ).Append( language );
            if ( !is_dir( outDir ) )
                make_directory( outDir );
            outFile = outDir;
            outFile.Append( "/" ).Append( xmlFile );
        }
    }
    layoutXml->Write( outFile );
    delete layoutXml;
}

void TranslateLayout::Merge()
{
    if ( mLanguages.size() )
        for ( std::vector<ByteString>::iterator i = mLanguages.begin();
              i != mLanguages.end(); ++i)
            MergeLanguage( *i );
    else
        MergeLanguage( mLanguage );
}

void TranslateLayout::CreateSDF()
{
    ByteString xmlFile = mFiles.front();
#ifndef WNT
    ByteString sdf = "/dev/stdout";
#else
    ByteString sdf = "\\\\.\\CON";
#endif
    if ( mOutput.Len() )
        sdf = mOutput;
    Export::SetLanguages( mLanguages );
    HelpParser::CreateSDF( sdf, mProject, mRoot, xmlFile,
                           new LayoutXMLFile( mMergeMode ), mGid1 );
}

void TranslateLayout::ExceptionalMain()
{
    ParseCommandLine();
    if ( mLanguages.size() )
        mLanguage = mLanguages.front();
    if ( mMergeMode )
        Merge();
    else
        CreateSDF();
}

void TranslateLayout::Main()
{
    try
    {
        ExceptionalMain();
    }
    catch ( xml::sax::SAXException& rExc )
    {
        OString aStr( OUStringToOString( rExc.Message,
                                         RTL_TEXTENCODING_ASCII_US ) );
        uno::Exception exc;
        if (rExc.WrappedException >>= exc)
        {
            aStr += OString( " >>> " );
            aStr += OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US );
        }
        fprintf( stderr, "error: parsing: '%s'\n", aStr.getStr() );
        OSL_ENSURE( 0, aStr.getStr() );
    }
    catch ( uno::Exception& rExc )
    {
        OString aStr( OUStringToOString( rExc.Message,
                                         RTL_TEXTENCODING_ASCII_US ) );
        fprintf( stderr, "error: UNO: '%s'\n", aStr.getStr() );
        OSL_ENSURE( 0, aStr.getStr() );
    }
}

TranslateLayout::TranslateLayout()
    : Application()
    , mGid1( "layout" )
    , mLanguage( "en-US" )
    , mLocalize( "localize.sdf" )
    , mOutput()
    , mProject( "layout" )
    , mRoot()
    , mMergeMode( false )
    , mLanguages()
    , mFiles()
{
}

TranslateLayout::~TranslateLayout()
{
}

SAL_IMPLEMENT_MAIN()
{
    TranslateLayout t;
    t.Main();
    return 0;
}