Statistics
| Revision:

svn-gvsig-desktop / trunk / install / launcher / izpack-launcher-1.3 / src / launcher.cpp @ 10374

History | View | Annotate | Download (30.7 KB)

1
/* Copyright (c) 2004 Julien Ponge - All rights reserved.
2
 * Some windows 98 debugging done by Dustin Sacks.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy
5
 * of this software and associated documentation files (the "Software"), to
6
 * deal in the Software without restriction, including without limitation the
7
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8
 * sell copies of the Software, and to permit persons to whom the Software is
9
 * furnished to do so, subject to the following conditions:
10
 *
11
 * The above copyright notice and this permission notice shall be included in
12
 * all copies or substantial portions of the Software.
13
 *
14
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20
 * IN THE SOFTWARE.
21
 */
22
#include <wx/string.h>
23
#include <wx/file.h>
24
#include <wx/filename.h>
25
#include <wx/url.h>
26
#include <wx/process.h>
27

    
28
#include "launcher.h"
29

    
30
#include "myIniReader.h"
31

    
32
#ifdef __UNIX__
33
  #include <stdlib.h>
34
  #include <map>
35
  #include <list>
36
#endif
37

    
38

    
39
/*
40
 * Helper function to run an external program. It takes care of the subtule
41
 * differences between the OS-specific implementations.
42
 *
43
 * @param cmd The command to run.
44
 * @return <code>true</code> in case of a success, <code>false</code> otherwise.
45
 */
46
bool run_external(wxString cmd)
47
{
48
 int code = wxExecute(cmd, wxEXEC_SYNC);
49
 return (code == 0);
50

    
51
}
52

    
53
bool run_external_async(wxString cmd)
54
{
55
 return (wxExecute(cmd, wxEXEC_ASYNC) != 0);
56
}
57

    
58
//wxString escape_backSlash(wxString aStr){
59
//  aStr.Replace("\\","\\\\");
60
//  return aStr;
61
//}
62

    
63
bool string_to_bool(wxString value, bool defaultValue){
64
 bool returnValue = defaultValue;
65
 if (value != wxEmptyString)
66
    if (
67
       value.CmpNoCase("s")   == 0  ||
68
       value.CmpNoCase("si")  == 0  ||
69
       value.CmpNoCase("1")   == 0  ||
70
       value.CmpNoCase("y")   == 0  ||
71
       value.CmpNoCase("yes") == 0
72
       ) 
73
    {
74
       returnValue = true;
75
    } else {
76
       returnValue = false;
77
    }
78
  return returnValue;
79
}
80

    
81
long LAUNCHAPP_TIMER_ID = wxNewId();
82

    
83
BEGIN_EVENT_TABLE(LauncherApp, wxApp)
84
    EVT_TIMER(LAUNCHAPP_TIMER_ID, LauncherApp::OnTimer)
85
END_EVENT_TABLE()
86

    
87

    
88
/* Main Application $Revision: 10374 $
89
 *
90
 * $Id: launcher.cpp 10374 2007-02-16 11:41:35Z jmvivo $
91
 */
92
LauncherApp::LauncherApp()
93
  : wxApp()
94
{
95
  APPLICATION_NAME = wxString(_("Launcher"));
96
  completed = false;
97

    
98
  SetAppName(_(APPLICATION_NAME));
99
  //loadParams();
100
}
101

    
102
void LauncherApp::echo(const wxString &msg) 
103
{
104
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK);
105
  dlg.ShowModal();
106
}
107

    
108
void LauncherApp::notifyToUser(const wxString &msg) 
109
{
110
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxICON_INFORMATION);
111
  dlg.ShowModal();
112
}
113

    
114

    
115
LauncherApp::~LauncherApp()
116
{
117

    
118
}
119

    
120
void LauncherApp::loadParams()
121
{
122
  //cfgName = wxString( "launcher.ini" );
123
  cfgName =wxString(argv[0]);
124
  wxFileName execFileName(cfgName);
125
  execFileName.SetExt("ini");
126
  cfgName = execFileName.GetFullPath();
127
  if (!wxFileExists(cfgName)) {    
128
    error(cfgName.Format(_("The configuration file '%s' does not exists."),cfgName.c_str()));
129
  }
130

    
131
  //wxFileInputStream in( cfgName );
132
  //wxFileConfig cfg( in );
133
  wxString downloadEnabled;
134
  wxString launchJarAsync;
135
  wxString askForCheckingProcess;
136
  wxString doChecks;
137
  wxString checksJREExecutionTerminationCode;
138
  wxString checksJai;
139
  wxString checksJaiIo;
140

    
141
  paramsApplicationName = readPathFromINI( "appname","gvSIG");
142
  paramsJar = readPathFromINI( "jar",wxEmptyString);
143
  paramsCommand = readPathFromINI( "command",wxEmptyString);
144
  paramsJre = readPathFromINI( "jre",   wxEmptyString);
145
  paramsJreDownload = readFromINI( "downloadJre", wxEmptyString);
146
  checksJai = readFromINI( "checkJai",wxEmptyString);
147
  paramsJai = readPathFromINI( "jai",wxEmptyString);
148
  paramsJaiDownload = readFromINI( "downloadJai",        wxEmptyString);
149
  checksJaiIo = readFromINI( "checkJai_io",wxEmptyString);
150
  paramsJaiIo = readPathFromINI( "jai_io",wxEmptyString);
151
  paramsJaiIoDownload = readFromINI( "downloadJai_io",wxEmptyString);
152
  paramsJreVersion = readFromINI( "jre_version",wxEmptyString);
153
  paramsJreVersionPrefered = readFromINI( "jre_version_prefered",wxEmptyString);
154
  downloadEnabled = readFromINI( "downloadEnabled",wxEmptyString);
155
  launchJarAsync = readFromINI( "launchJarAsync", wxEmptyString);
156
  askForCheckingProcess = readFromINI( "askForCheckingProcess", wxEmptyString);
157
  doChecks = readFromINI( "doChecks",wxEmptyString);
158
  checksJREExecutionTerminationCode = readFromINI( "checksJREExecutionTerminationCode",wxEmptyString);
159
  paramsJreHome = readPathFromINI( "jre_home", wxEmptyString);
160
  paramsLaunchMode = readPathFromINI( "launchMode", wxEmptyString);
161

    
162
  
163
  //echo(paramsCommand);
164

    
165
  //procesamos el parametro booleano 'downloadEnabled'
166
  paramsEnabledDownload =string_to_bool(downloadEnabled,false);
167
  //procesamos el parametro booleano 'launchJarAsync'
168
  paramsLaunchJarAsync =string_to_bool(launchJarAsync,false);
169
  //procesamos el parametro booleano 'askForCheckingProcess'
170
  paramsAskForCheckingProcess=string_to_bool(askForCheckingProcess,true);
171
  //procesamos el parametro booleano 'askForCheckingProcess'
172
  paramsDoChecks=string_to_bool(doChecks,true);
173
  //procesamos el parametro booleano 'checksJREExecutionTerminationCode'
174
  paramsChecksJREExecutionTerminationCode=string_to_bool(checksJREExecutionTerminationCode,true);
175
  paramsCheckJai=string_to_bool(checksJai,true);
176
  paramsCheckJaiIo=string_to_bool(checksJaiIo,true);
177

    
178
  
179
  if (paramsCommand == wxEmptyString )
180
  {
181
    error(cfgName.Format(_("The configuration file '%s' does not contain a command entry."),cfgName.c_str()));
182
  }
183
  if (paramsLaunchMode == wxEmptyString )
184
  {
185
    error(cfgName.Format(_("The configuration file '%s' does not contain a mode entry."),cfgName.c_str()));
186
  }
187
  paramsLaunchMode = paramsLaunchMode.MakeUpper();
188
  if ((!paramsLaunchMode.IsSameAs("APPLICATION")) && (!paramsLaunchMode.IsSameAs("INSTALL"))) {
189
        error(cfgName.Format(_("The configuration file '%s' contains a invalid mode entry."),cfgName.c_str()));
190
  }
191
  
192
  if (paramsJreVersionPrefered == wxEmptyString ) {
193
     paramsJreVersionPrefered = wxString(paramsJreVersion);
194
  }
195
  if ((!paramsDoChecks) && paramsJreHome == wxEmptyString) {
196
     error(cfgName.Format(_("The file entry 'jre_home' can not be empty when 'doChecks = No'."),cfgName.c_str()));
197
  }
198

    
199

    
200

    
201
  variables = sectionKeysFromINI("Variables");
202

    
203
  variablesValues = sectionKeysValuesFromINI("Variables",variables);
204

    
205

    
206
  size_t i;
207
  environVariables = sectionKeysFromINI("EnvironVariables");
208
  environVariablesValues = sectionKeysValuesFromINI("EnvironVariables",environVariables);
209
  // Hacemos sustituciones a los valores
210
  for (i=0; i < environVariables.GetCount() ;i++) {
211
         environVariablesValues[i]=parseEnviron(parseString(environVariablesValues[i])); 
212
  }
213

    
214
  //Las cargamos como variables de entorno
215
  for (i=0; i < environVariables.GetCount() ;i++) {
216
         wxSetEnv(environVariables[i], environVariablesValues[i]); 
217
  }
218
}
219

    
220
void LauncherApp::error(const wxString &msg)
221
{
222
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxICON_ERROR);
223
  dlg.ShowModal();
224
  printf(msg.c_str());
225
  exit(1);
226
}
227

    
228
void LauncherApp::confirm(const wxString &msg)
229
{
230
  int response;
231
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxCANCEL | wxICON_QUESTION );
232
  response = dlg.ShowModal();
233
  if (response != wxID_OK) {
234
    notifyToUser(_("Canceled by user"));
235
    exit(1);
236
  }
237
}
238
bool LauncherApp::confirmYesNoCancel(const wxString &msg,const int yesDefault = true)
239
{
240
  int response;
241
  long maskDefault;
242
  if (yesDefault) {
243
     maskDefault = wxYES_DEFAULT | wxYES_NO | wxCANCEL | wxICON_QUESTION;
244
  } else {
245
     maskDefault = wxNO_DEFAULT | wxYES_NO | wxCANCEL | wxICON_QUESTION;       
246
  }
247
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME),  maskDefault);
248
  response = dlg.ShowModal();
249
  if (response != wxID_YES && response != wxID_NO) {
250
    notifyToUser(_("Canceled by user"));
251
    exit(1);
252
  }
253
  return (response == wxID_YES);
254
 
255
}
256

    
257
void LauncherApp::showStatusWindow(){
258
  if (isStatusDialogVisible) {
259
    return;
260
  }
261
  
262
  statusDialog = new StatusDialog( APPLICATION_NAME );
263

    
264
  statusDialog->Centre();
265
  statusDialog->Show(TRUE);
266
  isStatusDialogVisible = true;
267
}
268

    
269

    
270
bool LauncherApp::OnInit()
271
{
272
  isStatusDialogVisible = false;
273
  wxFileName exeFileName(argv[0]);
274
  wxFileName exePath = exeFileName.GetPath();
275
  
276
  exePath.SetCwd();
277
  
278
  locale.Init();
279
  locale.AddCatalog("launcher");
280
  loadParams();  
281
  
282
  
283
  if (paramsLaunchMode.IsSameAs("INSTALL")){  
284
        APPLICATION_NAME = wxString(APPLICATION_NAME.Format(_("%s Install-Launcher"),paramsApplicationName.c_str()));
285
        SetAppName(_(APPLICATION_NAME));
286
        showStatusWindow();
287
  } else {
288
        APPLICATION_NAME = wxString(APPLICATION_NAME.Format(_("%s Launcher"),paramsApplicationName.c_str()));
289
        SetAppName(_(APPLICATION_NAME));
290
  }
291
  
292
  showStatusMsg(_("Intializing..."));
293
  
294
  myTimer = new wxTimer(this,LAUNCHAPP_TIMER_ID);
295
  myTimer->Start(150,true);
296
  this->MainLoop();
297
  return true;
298
}
299

    
300
void LauncherApp::fixSystemJREConfig(){
301
  showStatusMsg(_("Updating the system..."));
302
  if (localVersionToUse.Len() <= 5){
303
          // Estamos usando la rama x.x o x.x.x, no hace falta arreglar nada
304
          return;
305
  }
306
  //actualizamos CurrentVersion
307
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
308
                     "\\Java Runtime Environment\\";
309
                     
310
  wxString genericVersion = paramsJreVersion.Left(3);
311
  
312
  wxString baseKeyGeneric = baseKey + genericVersion + "\\";
313
  wxString baseKeyVersion = baseKey + localVersionToUse + "\\";
314

    
315
  wxRegKey *pRegKey = new wxRegKey(baseKey);
316
  if( !pRegKey->Exists() ) {
317
    error(_("JRE not found."));
318
  }
319
  
320
  // compiamos el contenido de la rama de la version
321
  // que queremos a la generica (1.4 o 1.5 o ...)
322
  wxRegKey *pRegKeyGeneric = new wxRegKey(baseKeyGeneric);
323
  wxRegKey *pRegKeyVersion = new wxRegKey(baseKeyVersion);
324
  
325
  if ( !pRegKeyGeneric->Exists() ){
326
    pRegKeyGeneric->Create();  
327
  }
328
  wxString tempKey;
329
  wxString tempValue;
330
  size_t nValues;
331
  
332
  pRegKeyVersion->GetKeyInfo(NULL,NULL,&nValues,NULL);
333
  long pos = 1;
334
  pRegKeyVersion->GetFirstValue(tempKey,pos);
335
  for(unsigned i=0;i<nValues;i++)        {
336
      //echo("copy " + tempKey);
337
      pRegKeyVersion->QueryValue(tempKey,tempValue);
338
      pRegKeyGeneric->SetValue(tempKey,tempValue);
339
      pRegKeyVersion->GetNextValue(tempKey,pos);
340
  }
341
    
342
  
343
}
344

    
345

    
346
bool LauncherApp::compareVersions(const wxString localVersion, const wxString requireVersion)
347
{
348
    bool result  = (localVersion.Cmp(requireVersion) == 0);
349
    /*
350
        if (requireVersion.Len() > localVersion.Len() )        {   
351
        
352
                result = (localVersion.Find(requireVersion) == 0);
353
        }
354
        else 
355
        {
356
                result = (requireVersion.Find(localVersion) == 0);
357
        }
358
        */
359

    
360
    /*
361
        if (result) {
362
            echo("localversion = '" + localVersion +"' requireVersion = '"+ requireVersion +"' ==> true");
363
    } else {
364
       echo("localversion = '" + localVersion +"' requireVersion = '"+ requireVersion +"' ==> false");
365
    }
366
    */
367
     
368
        return result;
369
}
370

    
371

    
372
bool LauncherApp::searchJRE()
373
{
374
  showStatusMsg(_("Searching JRE's..."));
375
  wxString version("");
376

    
377
  // Windows[tm] registry lookup
378
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
379
                     "\\Java Runtime Environment\\";
380

    
381
  wxRegKey bKey(baseKey);
382
  if (!bKey.Exists())  {
383
     return false;
384
  }
385

    
386
  if (!bKey.QueryValue("CurrentVersion", version)){
387
     return false;
388
  }
389
  
390
  if (version == "1.1") {
391
     return false;
392
  }
393

    
394
  wxString strTemp;
395
  wxRegKey sKey(baseKey);
396
  if (!compareVersions(version, paramsJreVersionPrefered)){
397
        //Nos recorremos las versiones instaladas
398
        version = "";
399
        if (sKey.HasSubKey(paramsJreVersionPrefered)) {
400
      version = wxString(paramsJreVersionPrefered);
401
    } else {              
402
      for(unsigned i=20;i>1;i--) {
403
        strTemp = wxString::Format(paramsJreVersion + "_%02d",i);
404
        if (sKey.HasSubKey(strTemp)) {
405
            version = strTemp;
406
          break;
407
        }
408
      }               
409
    }
410
  }
411

    
412
  if (version == "") {
413
    // comprobando x.x
414
    strTemp = paramsJreVersion.Left(3);
415
    if (sKey.HasSubKey(strTemp)) {
416
      version = strTemp;
417
    } else {
418
      if (paramsJreVersion.Len() >= 5) {
419
        // comprobando x.x.x
420
        strTemp = paramsJreVersion.Left(5);
421
        if (sKey.HasSubKey(strTemp)) {
422
          version = strTemp;
423
        }
424
       } 
425

    
426
    }
427
  }
428
        
429
  if (version == "") {
430
    // comprobando x.x.0
431
    strTemp = paramsJreVersion.Left(3)+".0";
432
    if (sKey.HasSubKey(strTemp)) {
433
      version = strTemp;
434
    }
435
  }            
436

    
437
  if (version == "") {
438
     return false;
439
  }            
440
  localVersionToUse = version;
441
  wxRegKey vKey(baseKey + version);
442

    
443
  if (!vKey.QueryValue("JavaHome", javaHome)){
444
     return false;
445
  }
446
  
447
  
448
  calculateJavaExePath(javaHome);
449
  /*
450
  echo("paramsJreVersion=" + paramsJreVersion);
451
  echo("paramsJreVersionPrefered=" + paramsJreVersionPrefered);
452
  echo("localVersionToUse=" + localVersionToUse);
453
  echo("javaHome=" +javaHome);
454
  echo("javaExecPath=" +javaExecPath);
455
  */
456
  return true;
457
}
458

    
459
void LauncherApp::runJRE()
460
{
461
  if (paramsLaunchMode.IsSameAs("INSTALL"))        {
462
    showStatusMsg(_("Launching installation..."));
463
  } else {
464
    showStatusMsg(_("Launching application..."));
465
  }
466
  wxString cmd = parseCommand();
467
  //echo(cmd);
468
  bool isOk=true;
469
  if (paramsLaunchJarAsync) {
470
      if (!run_external_async(cmd))
471
      {
472
        isOk=false;
473
      }
474
  } else {
475
      if (!run_external(cmd))
476
      {
477
        isOk=false;
478
      }  
479
  }
480
  
481
  if (!isOk) {
482
      if (paramsChecksJREExecutionTerminationCode) {
483
        error(
484
          cmd.Format(
485
            _("The command\n%s\ncould not be executed."),
486
            cmd.c_str()
487
          )
488
        );
489
      }
490
  } 
491

    
492
  completed = true;
493
}
494

    
495
void LauncherApp::jreInstall()
496
{
497
  showStatusWindow();
498
  
499
  showStatusMsg(_("Preparing to install JRE..."));
500
  
501
  if (!checkInstallerFile(paramsJre, paramsJreDownload,_("Java JRE version ")+paramsJreVersion))
502
  {
503
    error(_("The JRE could not be setup."));  
504
  }
505

    
506
  showStatusMsg(_("Installing JRE..."));
507
  if (!run_external(paramsJre))
508
  {
509
    error(_("The JRE could not be setup."));
510
  }
511
  if (!searchJRE()) {
512
    error(_("The JRE could not be setup."));
513
  }    
514
}
515

    
516

    
517
// Not used
518
void LauncherApp::netDownload()
519
{
520
  wxString browser;
521

    
522
#ifdef __WINDOWS__
523
  // We use the default browser.
524
  browser = "rundll32 url.dll,FileProtocolHandler ";
525
#endif
526

    
527
/*
528
  if (run_external(browser + paramsDownload))
529
  {
530
    completed = true;
531
  }
532
  else
533
  {
534
    error(_("Could not find a web browser."));
535
  }
536
  */
537
}
538

    
539
IMPLEMENT_APP(LauncherApp)
540

    
541

    
542
void LauncherApp::jaiInstall()
543
{
544
  if (!paramsCheckJai){
545
          return;
546
  }
547
  bool isOK;
548
  showStatusMsg(_("Checking JAI Library..."));
549
  
550
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
551
                     "\\Java Runtime Environment\\";
552

    
553
  wxString currentVersion;
554
  wxRegKey *pRegKey = new wxRegKey(baseKey);
555
  if( !pRegKey->Exists() )
556
    error(_("JRE not found."));
557
  if (!pRegKey->QueryValue("CurrentVersion", currentVersion)) error(_("JRE not found."));
558
  
559
  isOK=true;  
560
  if (!checksJai()) {
561
      //confirm(_("JAI library is required, Install it?"));
562
      showStatusWindow();
563
      
564
      showStatusMsg(_("Preparing to install JAI Library..."));
565
      if (!checkInstallerFile(paramsJai, paramsJaiDownload, _("JAI Library")))
566
      {
567
        isOK=false;  
568
      } else {
569
        pRegKey->SetValue("CurrentVersion",localVersionToUse);
570
        showStatusMsg(_("Preparing to install JAI Library..."));
571
        if (run_external(paramsJai))
572
        {
573
          isOK=(checksJai());
574
        } else {
575
          isOK=false;
576
        }  
577
        pRegKey->SetValue("CurrentVersion",currentVersion);
578
      }
579
      
580
  }  
581
  if (!isOK) {
582
    error(_("The JAI could not be setup."));
583
  }
584
}
585

    
586
void LauncherApp::jaiIoInstall()
587
{
588
  if (!paramsCheckJaiIo){
589
          return;
590
  }
591
  bool isOK;
592
  showStatusMsg(_("Checking JAI imageIO Library..."));
593
  
594
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
595
                     "\\Java Runtime Environment\\";
596

    
597
  wxString currentVersion;
598
  wxRegKey *pRegKey = new wxRegKey(baseKey);
599
  if( !pRegKey->Exists() )
600
    error(_("JRE not found."));
601
  if (!pRegKey->QueryValue("CurrentVersion", currentVersion)) error(_("JRE not found."));
602
  
603

    
604
  isOK=true;  
605
  if (!checksJaiIo()) {
606
      //confirm(_("JAI ImageIO library is required, Install it?"));
607
      showStatusWindow();
608
      
609
      showStatusMsg(_("Preparing to install JAI imageIO Library..."));
610
      if (!checkInstallerFile(paramsJaiIo, paramsJaiIoDownload,"JAI ImageIO Library"))
611
      {
612
        isOK=false;  
613
      } else {
614
        pRegKey->SetValue("CurrentVersion",localVersionToUse);
615
        showStatusMsg(_("Installing JAI imageIO Library..."));
616
        if (run_external(paramsJaiIo))
617
        {                                    
618
          isOK=(checksJaiIo());
619
        } else {
620
          isOK=false;        
621
        }
622
         pRegKey->SetValue("CurrentVersion",currentVersion);
623
      }
624
     
625
  }  
626
  if (!isOK) {
627
             error(_("The JAI imageIO could not be setup."));
628
  }
629
}
630

    
631
bool LauncherApp::checksJai(){
632
   return (wxFileExists(javaHome + "\\lib\\ext\\jai_core.jar"));
633
}
634

    
635
bool LauncherApp::checksJaiIo(){
636
   return (wxFileExists(javaHome + "\\lib\\ext\\jai_imageio.jar"));     
637
}
638

    
639
bool LauncherApp::downloadFileHttp(const wxString urlOfFile, const wxString filePath, const wxString msg){
640

    
641
  bool isOk;
642
  //echo(urlOfFile);
643
  if (urlOfFile == wxEmptyString) {
644
     return false;
645
  }
646
  
647
  if (filePath == wxEmptyString) {
648
     return false;
649
  }
650
  
651
  showStatusMsg(msg);
652
  wxURL url(urlOfFile);
653
  //echo("url open");
654
  wxInputStream *in_stream;
655

    
656
  in_stream = url.GetInputStream();
657
  //echo("in_stream open");
658
  if (!in_stream->IsOk()) {
659
     //echo("in_stream.IsOk == false");
660
     return false;
661
  }
662
  //echo("in_stream.IsOk == true");
663
  //echo("filePath =" + filePath);
664
  wxFileName fileName(filePath);
665
  
666
  
667
  // Preparamos la ruta para el fichero destino
668
  wxArrayString dirs;
669
  
670
  dirs = fileName.GetDirs();
671
  wxString dir;
672
  wxFileName curDir(".");
673
  for (size_t i=0; i < dirs.GetCount(); i++) {
674
      dir = dirs.Item(i);
675
      curDir.AppendDir(dir);
676
      //echo("dir " + curDir.GetPath());
677
      if (!curDir.DirExists()) {
678
         //echo("creating dir");
679
         isOk = curDir.Mkdir();
680
         if (!isOk) {
681
            //echo("dir create no ok");
682
            return false;
683
         }
684
         
685
         //echo("dir create ok");
686
      }
687
  }
688
  
689
  
690
  wxFileOutputStream out_stream  = wxFileOutputStream(filePath);
691
  //echo("out_stream open");
692
  
693
  //in_stream->Read(out_stream);
694
  size_t nbytes = 10240;
695
  char buffer[nbytes];
696
  
697
  
698
  //while (!in_stream->Eof()) {
699
  while (!in_stream->Eof()) {
700
      in_stream->Read(&buffer,nbytes);  
701
      if (in_stream->LastError() != wxSTREAM_NO_ERROR && in_stream->LastError() != wxSTREAM_EOF) {
702
          return false;
703
      }
704
      out_stream.Write(&buffer,in_stream->LastRead());
705
      if (out_stream.LastError() != wxSTREAM_NO_ERROR) {       
706
         return false;                                                                   
707
      }
708
      int totalKb = out_stream.GetSize() / 1024;
709
      wxString totalMsg =msg.Format("%i",totalKb);
710
      showStatusMsg(msg+" "+ totalMsg + " Kb");
711
      
712
  }
713
 
714
  
715
  isOk = true;
716
  /*
717
  if (isOk) {
718
    echo("isOk = true");
719
  } else {
720
    echo("isOk = false");         
721
  }
722
  */
723
  delete in_stream;
724
  
725
  //echo("end");
726
  return isOk;
727

    
728
}
729

    
730
bool LauncherApp::checkInstallerFile(const wxString filePath, const wxString urlDownload, const wxString fileDescription) {
731
  if (!wxFile::Exists(filePath))
732
  {
733
    if (paramsEnabledDownload) 
734
    {
735
      wxString msg = _("Installation requires to download this file:\n") + 
736
                     fileDescription + "\n" +
737
                     _("Do you want to continue?");
738
      confirm(msg);
739
      //showStatusMsg(_("Downloading ") + fileDescription + "...");      
740
      if (!downloadFileHttp(urlDownload,filePath,_("Downloading ") + fileDescription + "..." )) 
741
      {
742
        //FIXME: Falta msgError
743
        return false;  
744
      }       
745
    }
746
    else
747
    {
748
      return false;  
749
    }
750

    
751
  }
752
  return true;
753
}
754

    
755
void LauncherApp::showStatusMsg(const wxString msg) {
756
  if (isStatusDialogVisible) {
757
     while (this->Pending()) {
758
           this->Dispatch();
759
     }
760
     if (statusDialog->IsCanceled()) {
761
        int response;
762
        wxMessageDialog dlg(0, _("Do you really want to cancel the installation process?"), _(APPLICATION_NAME), wxYES_NO | wxICON_QUESTION );
763
        response = dlg.ShowModal();
764
        if (response == wxID_YES) {
765
            notifyToUser(_("Canceled by user"));
766
            exit(1);
767
        }
768
        statusDialog->DoNotCancel();
769
     }
770
     statusDialog->showStatus(msg);
771
  }
772
}
773

    
774
bool LauncherApp::checkVersion(const wxString javaexe)
775
{
776
     wxString cmd;
777
     wxArrayString out;
778
     wxArrayString err;
779
     
780
     cmd = cmd.Format("%s -version", javaexe.c_str());
781
     if( wxExecute(cmd,out,err)!= 0 ) {
782
         notifyToUser(_("Failed checking JVM version."));      
783
         return false;
784
     }
785
     
786
     if (err.Count() == 0) {
787
         notifyToUser(_("Failed checking JVM version."));      
788
         return false;        
789
     }
790
     
791
     if (err[0].Contains(paramsJreVersion.c_str()) && err[0].Contains("version")) {
792
        return true; 
793
     }
794
     notifyToUser(cmd.Format(_("%s\nJava %s recommended"), err[0].c_str(),paramsJreVersion.c_str()));
795
     return false;
796

    
797

    
798
}
799

    
800
void LauncherApp::run(){
801
  bool doChecks =true;
802
                  
803
  if (!paramsDoChecks) {
804
    javaHome = paramsJreHome;
805
    calculateJavaExePath(javaHome);
806
  } else {
807
      if (paramsAskForCheckingProcess) {
808
         wxString msg = _("Do you want to check the application requirements? \nThis will install missing components (Recommended).");
809
         doChecks = confirmYesNoCancel(msg,true);
810
         if (!doChecks) {
811
                // No quiere comprobacion, por lo que solicitamos 
812
                wxString msgDir = _("Please, select the Java VM.");   
813
                wxFileDialog dlg(
814
                    0,
815
                    msgDir,
816
                    wxEmptyString,
817
                    wxString("java.exe"),
818
                    wxString("Java VM executable file (java.exe)|java.exe"),
819
                    wxOPEN | wxFILE_MUST_EXIST,
820
                    wxDefaultPosition
821
                );
822
                int response = dlg.ShowModal();  
823
                if (response != wxID_OK) {
824
                   notifyToUser(_("Canceled by user"));
825
                   exit(1);
826
                }
827
                //caragamos la variable con el eljecutable
828
                javaExecPath = dlg.GetPath();
829
                
830
                checkVersion(javaExecPath);
831
                
832
                //generamos el path para el JavaHome (por si acaso)
833
                wxFileName fileName(javaExecPath);
834
                fileName.SetFullName("");
835
                fileName.AppendDir("..");
836
                fileName.Normalize();
837
                javaHome = fileName.GetPath();                 
838
                 
839
         }
840
      }
841
         
842
    
843
      if (doChecks) {
844
    
845
          if (!searchJRE())
846
          {
847
            jreInstall();
848
          }
849
        
850
          fixSystemJREConfig();
851
        
852
          jaiInstall();
853
        
854
          jaiIoInstall();
855
      }
856
  }
857

    
858
  copyRequiredFiles();
859

    
860
  runJRE();
861

    
862
  exit(0);    
863
     
864
}
865

    
866
void LauncherApp::OnTimer(wxTimerEvent& event) {     
867
     run();
868
}
869

    
870
void LauncherApp::calculateJavaExePath(const wxString aJavaHome){
871
  int osVerMayor;
872
  int osVerMinor;
873

    
874
  wxGetOsVersion(&osVerMayor,&osVerMinor);
875
  if (osVerMayor < 5) {
876
    javaExecPath = aJavaHome + "\\bin\\java";
877
  }else{
878
    javaExecPath = aJavaHome + "\\bin\\javaw";
879
  }
880
    
881
}
882

    
883

    
884
wxString LauncherApp::parseCommand(){
885

    
886
  return parseString(paramsCommand);
887
}
888

    
889
wxString LauncherApp::parseString(const wxString theString){
890
  wxString resultCommand(theString);
891

    
892
  // #JAVA#
893
  resultCommand.Replace("#JAVA#",javaExecPath.c_str());
894
  
895
  // #JAVA_HOME#
896
  resultCommand.Replace("#JAVA_HOME#",javaHome.c_str());
897

    
898
  // #JAR#
899
  resultCommand.Replace("#JAR#",paramsJar.c_str());
900

    
901
  // calculamos la cadena args y sustituimos los #ARG?#
902
  wxString theArgs("");
903
  wxString theArg("");
904
  int i;
905
  for (i=1;i<this->argc;i++) {
906
    theArg = argv[i];
907
    if (i!=1){
908
            theArgs = theArgs + " \"" + theArg + "\"";
909
    }else{
910
            theArgs = "\"" + theArg + "\"";
911
    }
912

    
913
    resultCommand.Replace(theArg.Format("\"#ARG%i#\"",i),theArg.c_str());
914
  }
915
  // Dejamos a blanco los argumento que no hemos recivido y existen en el comando
916
  theArg = "";
917
  for (i=i;i<10;i++) {
918
    resultCommand.Replace(theArg.Format("#ARG%i#",i),theArg.c_str());
919
  }
920
  //echo(theArgs);
921

    
922
  // #ARGS#
923
  resultCommand.Replace("#ARGS#",theArgs.c_str());
924
  
925
  // #ARG0#
926
  resultCommand.Replace("#ARG0#",argv[0]);
927

    
928
  // variables de la seccion variables
929

    
930
  //echo(resultCommand);
931
  
932
//  
933
  if (!variables.IsEmpty()){
934
          //echo(theArg.Format("No empty: count =%i",keys.GetCount()));
935
          unsigned int i;
936
          for (i=0;i<variables.GetCount();i++){
937
                  //echo("#"+variables[i]+"#="+variablesValues[i]);
938
                  resultCommand.Replace("#"+variables[i]+"#",variablesValues[i]);
939
          }
940

    
941
  //echo(resultCommand);
942

    
943
  }
944

    
945
 
946

    
947
  return resultCommand;
948
}
949

    
950
wxString LauncherApp::parseEnviron(const wxString theString){
951
  //echo("in string:"+theString);
952
  wxString resultString("");
953
  wxString token("");
954
  size_t pos = 0;
955
  bool startedToken=false;
956
  char character;
957
  wxString env;
958
  while (pos < theString.Len()){
959
    character =theString.GetChar(pos);
960
    //echo(token.Format("%i=%c",pos,character));
961
    if (character == '%'){
962
      //echo("mark");
963
      if (startedToken){
964
         if (wxGetEnv(token, &env)){
965
           //echo("token Found:"+env);
966
           resultString += env; 
967
         }else{
968
           //echo("token not Found:"+token);
969
           resultString += "%" + token + "%"; 
970
         }
971
         token="";
972
         startedToken = false;
973
      } else {
974
         startedToken = true;
975
      }
976
    
977
    }else {
978
      //echo("no mark");
979
      if (startedToken){
980
        token += character;
981
        //echo("token:"+token);
982
      } else {
983
        resultString += character;
984
        //echo("result:"+resultString);
985
      }
986
    }
987
    pos++;
988
  }
989
  //echo("tempResult:"+resultString);
990
  if (!environVariables.IsEmpty()){
991
    for (size_t i=0; i < environVariables.GetCount(); i++){
992
      //echo("replace:%"+environVariables[i] + "%");
993
      //echo("for "+environVariablesValues[i]);
994
      //echo("in string "+ resultString);
995
      resultString.Replace("%"+environVariables[i]+"%",environVariablesValues[i]);
996
    }
997
  }
998
  //echo("Final Result:"+resultString);
999
  return resultString;
1000
}
1001

    
1002

    
1003
bool LauncherApp::copyRequiredFiles(){
1004
  int i = 0;
1005
  //wxFileInputStream in( cfgName );
1006
  //wxFileConfig cfg( in );
1007
  //cfg.SetPath("/CopyRequiredFiles");
1008

    
1009
  wxString source;
1010
  wxString target;
1011
  wxString msg;
1012
  wxFileName fileName;
1013

    
1014
  while (true) {
1015
        i++;
1016

    
1017
        source = readPathFromINI("CopyRequiredFiles",source.Format("source%i",i),wxEmptyString);
1018
        target = readPathFromINI("CopyRequiredFiles",target.Format("target%i",i),wxEmptyString);
1019
        if (source == wxEmptyString && target == wxEmptyString) {
1020
                return true;
1021
        }
1022
        if (source == wxEmptyString || target == wxEmptyString) {
1023
                error(source.Format(_("Error copying the file number %i:\n missing source or target entry"),i));
1024
                return false;
1025
        }
1026
        source = parseString(source);
1027
        target = parseString(target);
1028
        if (wxFileExists(target)){
1029
                continue;
1030
        } else {
1031
            if (wxDirExists(target)) {
1032
                fileName = wxFileName(target);
1033
                wxFileName tempFileName(source);
1034
                fileName.SetFullName(tempFileName.GetFullName());
1035
                if (fileName.FileExists()) {
1036
                        continue;
1037
                }
1038
            }
1039
                                
1040
        }
1041
        if (!wxFileExists(source)){
1042
                error(source.Format(_("Error copying the file number %i:\n source file '%s' does not exists."),i,source.c_str()));
1043
                return false;
1044
        }
1045

    
1046
        fileName = wxFileName(source);
1047
        msg = msg.Format(_("copying %s..."), fileName.GetFullName().c_str());
1048
        //echo(msg);
1049
        //echo(msg.Format("%s --> %s",source.c_str(),target.c_str()));
1050
        if (!copyFile(source,target, msg)){
1051
                error(source.Format(_("Error copying the file number %i:\n '%s' --> '%s'."),i,source.c_str(),target.c_str()));
1052
                return false;
1053
        }
1054

    
1055
  }
1056
}
1057

    
1058
bool LauncherApp::copyFile(const wxString source, const wxString target, const wxString msg){
1059

    
1060
  bool isOk;
1061
  //echo(source);
1062
  if (source == wxEmptyString) {
1063
     return false;
1064
  }
1065
  
1066
  //echo(target);
1067
  if (target == wxEmptyString) {
1068
     return false;
1069
  }
1070
  
1071
  showStatusMsg(msg);
1072

    
1073
  wxFileName targetFileName(target);
1074
  
1075
  
1076
  // Preparamos la ruta para el fichero destino
1077
  wxArrayString dirs;
1078
  
1079
  dirs = targetFileName.GetDirs();
1080
  wxString dir;
1081
  wxFileName curDir;
1082
  if (targetFileName.IsAbsolute()) {
1083
        curDir.Assign("\\");
1084
        curDir.SetVolume(targetFileName.GetVolume());
1085
  }else{
1086
        curDir.Assign(".");
1087
  }
1088
  for (size_t i=0; i < dirs.GetCount(); i++) {
1089
      dir = dirs.Item(i);
1090
      curDir.AppendDir(dir);
1091
      //echo("dir " + curDir.GetPath());
1092
      if (!curDir.DirExists()) {
1093
         //echo("creating dir");
1094
         isOk = curDir.Mkdir();
1095
         if (!isOk) {
1096
            //echo("dir create no ok");
1097
            return false;
1098
         }
1099
         
1100
         //echo("dir create ok");
1101
      }
1102
  }
1103

    
1104
  wxString finalTarget;
1105
  if (targetFileName.IsDir() || targetFileName.DirExists()) { 
1106
      //echo("targetFileName.IsDir -> true  " + targetFileName.GetFullPath());
1107
      wxFileName sourceFileName(source);
1108
      targetFileName.SetFullName(sourceFileName.GetFullName());
1109
      finalTarget = targetFileName.GetFullPath();
1110
  } else {
1111
      //echo("targetFileName.IsDir -> false  " + targetFileName.GetFullPath());
1112
      finalTarget = target;
1113
  }
1114

    
1115

    
1116
  //echo(msg.Format("%s --> %s",source.c_str(),finalTarget.c_str()));
1117
  isOk = wxCopyFile(source,finalTarget,false);
1118
        
1119

    
1120
  return isOk;
1121

    
1122
}
1123

    
1124
wxString LauncherApp::readPathFromINI(wxString section, wxString key, const wxString defaultValue){
1125
        char* charResult;
1126

    
1127
        charResult =myGetPrivateProfileString(section.c_str(),key.c_str(),defaultValue.c_str(),cfgName.c_str()); 
1128

    
1129
        //Remplazamos \ por /
1130
        
1131
        register char* s = charResult;
1132
        for (;*s;s++) {
1133
                if (*s == '\\') {
1134
                        *s = '/';
1135
                }
1136
        }
1137

    
1138
        wxString result(charResult);
1139
        return result;
1140

    
1141

    
1142
}
1143

    
1144

    
1145

    
1146
wxString LauncherApp::readPathFromINI(wxString key, const wxString defaultValue){
1147
        return readPathFromINI("default",key,defaultValue);
1148

    
1149
}
1150

    
1151
wxString LauncherApp::readFromINI(wxString section, wxString key, const wxString defaultValue){
1152
        char* charResult;
1153

    
1154
        charResult =myGetPrivateProfileString(section.c_str(),key.c_str(),defaultValue.c_str(),cfgName.c_str()); 
1155

    
1156
        wxString result(charResult);
1157
        return result;
1158
}
1159

    
1160
wxString LauncherApp::readFromINI(wxString key, const wxString defaultValue){
1161
        return readFromINI("default",key,defaultValue);
1162
}
1163

    
1164
wxArrayString LauncherApp::sectionKeysFromINI(const wxString section){
1165
        char* charResult;
1166

    
1167
        charResult =myGetPrivateProfileString(section.c_str(),NULL,NULL,cfgName.c_str()); 
1168

    
1169

    
1170
        wxArrayString rvalue;
1171
        wxString token = wxString("");
1172

    
1173
        for (int i=0; i < 2048;i++){
1174
           if (charResult[i] == 0){
1175
                if (token == ""){
1176
                  return rvalue;
1177
                }
1178
                rvalue.Add(token);
1179
                token = wxString("");
1180
           }else{
1181
             token.Append(charResult[i]);
1182
           }
1183
        }
1184
        return rvalue;
1185
}
1186

    
1187

    
1188
wxArrayString LauncherApp::sectionKeysValuesFromINI(const wxString section,wxArrayString keys) {
1189
        wxArrayString rvalue;
1190
        unsigned int i;
1191
        wxString key;
1192
        wxString value;
1193
        for (i=0;i < keys.GetCount(); i++){
1194
                rvalue.Add(readPathFromINI( section, keys[i], "")); 
1195
        }        
1196
        return rvalue;
1197
}
1198