Statistics
| Revision:

root / trunk / install / launcher / izpack-launcher-1.3_windows / src / launcher.cpp @ 11445

History | View | Annotate | Download (33.3 KB)

1 8474 jmvivo
/* 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
27
#include "launcher.h"
28
29
#ifdef __UNIX__
30
  #include <stdlib.h>
31
  #include <stdio.h>
32
  #include <map>
33
  #include <list>
34
#endif
35
36
37
/*
38
 * Helper function to run an external program. It takes care of the subtule
39
 * differences between the OS-specific implementations.
40
 *
41
 * @param cmd The command to run.
42
 * @return <code>true</code> in case of a success, <code>false</code> otherwise.
43
 */
44
bool run_external(wxString cmd)
45
{
46
 int code = wxExecute(cmd, wxEXEC_SYNC);
47
 return (code == 0);
48
49
}
50
51
52
bool run_external_async(wxString cmd)
53
{
54
 return (wxExecute(cmd, wxEXEC_ASYNC) != 0);
55
}
56
57
bool run_external_withOut(wxString cmd,wxArrayString& out, wxArrayString& errors){
58
        //printf(" run_external_withOut **%s**\n",cmd.c_str());
59
        int exitCode =wxExecute(cmd, out,errors);
60
        //printf("\texitCode= %i, out.Count = %i, error.Count= %i\n",exitCode,out.Count(),errors.Count());
61
62
        /*
63
        int i;
64
        for (i=0;i<out.Count();i++){
65
                printf("\t\tout: %s\n",out[i].c_str());
66
        }
67
        for (i=0;i<errors.Count();i++){
68
                printf("\t\terrors: %s\n",errors[i].c_str());
69
        }
70
        */
71
72
        return ( exitCode == 0);
73
}
74
75
76
bool string_to_bool(wxString value, bool defaultValue){
77
 bool returnValue = defaultValue;
78
 if (value != wxEmptyString)
79
    if (
80
       value.CmpNoCase("s")   == 0  ||
81
       value.CmpNoCase("si")  == 0  ||
82
       value.CmpNoCase("1")   == 0  ||
83
       value.CmpNoCase("y")   == 0  ||
84
       value.CmpNoCase("yes") == 0
85
       )
86
    {
87
       returnValue = true;
88
    } else {
89
       returnValue = false;
90
    }
91
  return returnValue;
92
}
93
94
95
long LAUNCHAPP_TIMER_ID = wxNewId();
96
97
BEGIN_EVENT_TABLE(LauncherApp, wxApp)
98
    EVT_TIMER(LAUNCHAPP_TIMER_ID, LauncherApp::OnTimer)
99
END_EVENT_TABLE()
100
101
102
/* Main Application $Revision$
103
 *
104
 * $Id$
105
 */
106
LauncherApp::LauncherApp()
107
  : wxApp()
108
{
109
  APPLICATION_NAME = wxString(_("Launcher"));
110
111
112
  SetAppName(_( APPLICATION_NAME ));
113
}
114
115
void LauncherApp::echo(const wxString &msg)
116
{
117
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK);
118
  dlg.ShowModal();
119
}
120
121
void LauncherApp::notifyToUser(const wxString &msg)
122
{
123
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxICON_INFORMATION);
124
  dlg.ShowModal();
125
}
126
127
void LauncherApp::notifyErrorToUser(const wxString &msg)
128
{
129
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxICON_ERROR);
130
  dlg.ShowModal();
131
}
132
133
134
LauncherApp::~LauncherApp()
135
{
136
137
}
138
139
void LauncherApp::loadParams()
140
{
141
  //cfgName = wxString( "launcher.ini" );
142
  cfgName =wxString(argv[0]);
143
  wxFileName execFileName(cfgName);
144
  execFileName.Normalize();
145
  execFileName.SetExt("ini");
146
  cfgName = execFileName.GetFullPath();
147
  if (!wxFileExists(cfgName)) {
148
    error(cfgName.Format(_("The configuration file '%s' does not exists."),cfgName.c_str()));
149
  }
150
  wxString downloadEnabled;
151
  wxString launchJarAsync;
152
  wxString doChecks;
153
154
155
  paramsApplicationName = readPathFromINI( "appname","gvSIG");
156
  paramsJar = readPathFromINI( "jar",wxEmptyString);
157
  paramsCommand = readPathFromINI( "command",wxEmptyString);
158
159
  paramsJre = readPathFromINI( "jre",   wxEmptyString);
160
  paramsJreDownload = readFromINI( "downloadJre", wxEmptyString);
161
162
  paramsProvidedJre = readPathFromINI( "jreProvided",wxEmptyString);
163
  paramsProvidedJreDownload = readPathFromINI( "downloadjreProvided",   wxEmptyString);
164
  paramsProvidedJreInstalledJavaHome = readPathFromINI( "jreProvidedJavaHome",   wxEmptyString);
165
  paramsProvidedJreInstalledRootDirectory = readPathFromINI( "jreProvidedRootDirectory",   wxEmptyString);
166
  paramsProvidedJreInstallCmd = readFromINI("jreProvidedInstallCommand", wxEmptyString);
167
168
169
170
  paramsJai = readPathFromINI( "jai",              wxEmptyString);
171
  paramsJaiDownload = readFromINI( "downloadJai",        wxEmptyString);
172
  paramsJaiIo = readPathFromINI( "jai_io",wxEmptyString);
173
  paramsJaiIoDownload = readFromINI( "downloadJai_io",wxEmptyString);
174
175
  paramsJreVersion = readFromINI( "jre_version",wxEmptyString);
176
  paramsJreVersionPrefered = readFromINI( "jre_version_prefered",wxEmptyString);
177
178
  downloadEnabled = readFromINI( "downloadEnabled",wxEmptyString);
179
  launchJarAsync = readFromINI( "launchJarAsync", wxEmptyString);
180
  doChecks = readFromINI( "doChecks",wxEmptyString);
181
  paramsJreHome = readPathFromINI( "jre_home", wxEmptyString);
182
  paramsLaunchMode = readPathFromINI( "launchMode", wxEmptyString);
183
184
185
186
  //procesamos el parametro booleano 'downloadEnabled'
187
  paramsEnabledDownload =string_to_bool(downloadEnabled,false);
188
  //procesamos el parametro booleano 'launchJarAsync'
189
  paramsLaunchJarAsync =string_to_bool(launchJarAsync,false);
190
  //procesamos el parametro booleano 'doChekc'
191
  paramsDoChecks=string_to_bool(doChecks,true);
192
193
  if (paramsCommand == wxEmptyString )
194
  {
195
    error(cfgName.Format(_("The configuration file '%s' does not contain a command entry."),cfgName.c_str()));
196
  }
197
  if (paramsLaunchMode == wxEmptyString )
198
  {
199
    error(cfgName.Format(_("The configuration file '%s' does not contain a mode entry."),cfgName.c_str()));
200
  }
201
  paramsLaunchMode = paramsLaunchMode.MakeUpper();
202
  if ((!paramsLaunchMode.IsSameAs("APPLICATION")) && (!paramsLaunchMode.IsSameAs("INSTALL"))) {
203
        error(cfgName.Format(_("The configuration file '%s' contains a invalid mode entry."),cfgName.c_str()));
204
  }
205
206
  if (paramsJreVersionPrefered == wxEmptyString ) {
207
     paramsJreVersionPrefered = wxString(paramsJreVersion);
208
  }
209
  if ((!paramsDoChecks) && paramsJreHome == wxEmptyString) {
210
     error(cfgName.Format(_("The file entry 'jre_home' can not be empty when 'doChecks = No'."),cfgName.c_str()));
211
  }
212
213
214
215
  variables = sectionKeysFromINI("Variables");
216
217
  variablesValues = sectionKeysValuesFromINI("Variables",variables);
218
219
}
220
221
void LauncherApp::error(const wxString &msg)
222
{
223
  wxMessageDialog dlg(0, msg, _(APPLICATION_NAME), wxOK | wxICON_ERROR);
224
  dlg.ShowModal();
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
258
259
bool LauncherApp::OnInit()
260
{
261
  isStatusDialogVisible = false;
262
  wxFileName exeFileName(argv[0]);
263
  exeFileName.Normalize();
264
  wxFileName exePath = exeFileName.GetPath();
265
  exePath.Normalize();
266
267
  exePath.SetCwd();
268
269
  locale.Init();
270
  locale.AddCatalog("launcher");
271
  loadParams();
272
273
274
  if (paramsLaunchMode.IsSameAs("INSTALL")){
275
        APPLICATION_NAME = wxString(APPLICATION_NAME.Format(_("%s Install-Launcher"),paramsApplicationName.c_str()));
276
        SetAppName(_(APPLICATION_NAME));
277
        showStatusWindow();
278
  } else {
279
        APPLICATION_NAME = wxString(APPLICATION_NAME.Format(_("%s Launcher"),paramsApplicationName.c_str()));
280
        SetAppName(_(APPLICATION_NAME));
281
  }
282
283
  showStatusMsg(_("Intializing..."));
284
285
  myTimer = new wxTimer(this,LAUNCHAPP_TIMER_ID);
286
  myTimer->Start(150,true);
287
  this->MainLoop();
288
  return true;
289
}
290
291
bool LauncherApp::compareVersions(const wxString localVersion, const wxString requireVersion)
292
{
293
    bool result  = (localVersion.Cmp(requireVersion) == 0);
294
    /*
295
        if (requireVersion.Len() > localVersion.Len() )        {
296

297
                result = (localVersion.Find(requireVersion) == 0);
298
        }
299
        else
300
        {
301
                result = (requireVersion.Find(localVersion) == 0);
302
        }
303
        */
304
305
    /*
306
        if (result) {
307
            echo("localversion = '" + localVersion +"' requireVersion = '"+ requireVersion +"' ==> true");
308
    } else {
309
       echo("localversion = '" + localVersion +"' requireVersion = '"+ requireVersion +"' ==> false");
310
    }
311
    */
312
313
        return result;
314
}
315
316
317
void LauncherApp::runJRE()
318
{
319
  if (paramsLaunchMode.IsSameAs("INSTALL"))        {
320
    showStatusMsg(_("Launching installation..."));
321
  } else {
322
    showStatusMsg(_("Launching application..."));
323
  }
324
  wxString cmd = parseCommand();
325
  if (paramsLaunchJarAsync) {
326
      if (!run_external_async(cmd))
327
      {
328
         error(cmd.Format(_("The command\n%s\ncould not be executed."),cmd.c_str()));
329
      }
330
  } else {
331
      if (!run_external(cmd))
332
      {
333
        error(cmd.Format(_("The command\n%s\ncould not be executed."),cmd.c_str()));
334
      }
335
  }
336
337
}
338
339
wxString LauncherApp::installProvidedJRE(){
340
        showStatusWindow();
341
        showStatusMsg(_("Preparing to install Provided JRE..."));
342
343
        if (!checkInstallerFile(paramsProvidedJre, paramsProvidedJreDownload,_("Java JRE version ")+paramsJreVersion))
344
        {
345
                notifyErrorToUser(_("The JRE could not be setup."));
346
                return "";
347
        }
348
349
        showStatusMsg(_("Installing Provided JRE..."));
350
351
        wxString cmd = parseString(paramsProvidedJreInstallCmd);
352
353
        if (!run_external(cmd))
354
        {
355
                notifyErrorToUser(_("The JRE could not be setup."));
356
                return "";
357
        }
358
359
        wxString myJavaFile = calculateJavaExePath(parseString(paramsProvidedJreInstalledJavaHome));
360
361
        if (!wxFileExists(myJavaFile)){
362
                notifyErrorToUser(wxString::Format(_("The file %s does not exist."),myJavaFile.c_str()));
363
                return "";
364
          }
365
366
  return myJavaFile;
367
368
}
369
370
IMPLEMENT_APP(LauncherApp)
371
372
bool LauncherApp::downloadFileHttp(const wxString urlOfFile, const wxString filePath, const wxString msg){
373
374
  bool isOk;
375
  //echo(urlOfFile);
376
  if (urlOfFile == wxEmptyString) {
377
     return false;
378
  }
379
380
  if (filePath == wxEmptyString) {
381
     return false;
382
  }
383
384
  showStatusMsg(msg);
385
  wxURL url(urlOfFile);
386
  //echo("url open");
387
  wxInputStream *in_stream;
388
389
  in_stream = url.GetInputStream();
390
  //echo("in_stream open");
391
  if (!in_stream){
392
        return false;
393
  }
394
  if (!in_stream->IsOk()) {
395
     //echo("in_stream.IsOk == false");
396
     return false;
397
  }
398
  //echo("in_stream.IsOk == true");
399
  //echo("filePath =" + filePath);
400
  wxFileName fileName(filePath);
401
  fileName.Normalize();
402
  wxFileName fileDir(fileName.GetPath());
403
  if (!fileDir.DirExists()) {
404
        if (!fileDir.Mkdir(0777,wxPATH_MKDIR_FULL )) {
405
                return false;
406
        }
407
  }
408
409
  wxFileOutputStream out_stream  = wxFileOutputStream(filePath);
410
  //echo("out_stream open");
411
412
  //in_stream->Read(out_stream);
413
  size_t nbytes = 10240;
414
  char buffer[nbytes];
415
416
417
  while (!in_stream->Eof()) {
418
      in_stream->Read(&buffer,nbytes);
419
      if (in_stream->LastError() != wxSTREAM_NO_ERROR && in_stream->LastError() != wxSTREAM_EOF) {
420
          return false;
421
      }
422
      out_stream.Write(&buffer,in_stream->LastRead());
423
      if (out_stream.LastError() != wxSTREAM_NO_ERROR) {
424
         return false;
425
      }
426
      int totalKb = out_stream.GetSize() / 1024;
427
      wxString totalMsg =wxString::Format("%i",totalKb);
428
      showStatusMsg(msg+" "+ totalMsg + " Kb");
429
430
  }
431
432
433
  isOk = true;
434
 /*
435
  if (isOk) {
436
    echo("isOk = true");
437
  } else {
438
    echo("isOk = false");
439
  }
440
 */
441
  delete in_stream;
442
443
  //echo("end");
444
  return isOk;
445
446
}
447
448
bool LauncherApp::checkInstallerFile(const wxString filePath, const wxString urlDownload, const wxString fileDescription) {
449
  if (!wxFile::Exists(filePath))
450
  {
451
    if (paramsEnabledDownload)
452
    {
453
      wxString msg;
454
      msg = wxString::Format(_("The installation requires to download this file:\n%s\nDo you want to continue?"),fileDescription.c_str());
455
      confirm(msg);
456
      msg = wxString::Format(_("Downloading %s..."),fileDescription.c_str());
457
      if (!downloadFileHttp(urlDownload,filePath,msg))
458
      {
459
        //FIXME: Falta msgError
460
        return false;
461
      }
462
    }
463
    else
464
    {
465
      return false;
466
    }
467
468
  }
469
  return true;
470
}
471
472
void LauncherApp::showStatusMsg(const wxString msg) {
473
  if (isStatusDialogVisible) {
474
     while (this->Pending()) {
475
           this->Dispatch();
476
     }
477
     if (statusDialog->IsCanceled()) {
478
        int response;
479
        wxMessageDialog dlg(0, _("Are you sure you want to cancel installation?"), _(APPLICATION_NAME), wxYES_NO | wxICON_QUESTION );
480
        response = dlg.ShowModal();
481
        if (response == wxID_YES) {
482
            notifyToUser(_("Canceled by the user"));
483
            exit(1);
484
        }
485
        statusDialog->DoNotCancel();
486
     }
487
     statusDialog->showStatus(msg);
488
  }
489
}
490
491
void LauncherApp::run(){
492
  bool ok = false;
493
494
  wxString mJavaFileName;
495
  wxString errorMsg;
496
  if (paramsLaunchMode.IsSameAs("INSTALL")){
497
          showSelectionDialog();
498
  }else{
499
          if (!paramsDoChecks) {
500
                  setJavaExePath(calculateJavaExePath(paramsJreHome));
501
          } else {
502
                errorMsg = checkJava(mJavaFileName);
503
                //echo("check result: *"+errorMsg+"*");
504
                if (errorMsg.Cmp("") == 0) {
505
                        setJavaExePath(mJavaFileName);
506
                        ok=true;
507
                } else {
508
                        wxString msg =wxString::Format(_("Problems found in the selected JRE:\n%s\n\nDo you want to continue?"),errorMsg.c_str());
509
                        if (confirmYesNoCancel(msg,false)) {
510
                                setJavaExePath(mJavaFileName);
511
                        } else {
512
                                notifyToUser(_("Launch installation program to try to repare the problem."));
513
                                notifyToUser(_("Canceled by the user"));
514
                                exit(1);
515
                        }
516
                }
517
          }
518
519
520
  }
521
522
  copyRequiredFiles();
523
524
  runJRE();
525
526
  exit(0);
527
528
}
529
530
void LauncherApp::OnTimer(wxTimerEvent& event) {
531
     run();
532
}
533
534
wxString LauncherApp::selectJavaExeFileManualy() {
535
    wxString msgDir = _("Manually select the Java VM");
536
    wxFileDialog dlg(
537
        0,
538
        msgDir,
539
        wxEmptyString,
540
        wxString("java.exe"),
541
        wxString( wxString(_("Java VM executable file")) + " (java.exe)|java.exe"),
542
        wxOPEN | wxFILE_MUST_EXIST,
543
        wxDefaultPosition
544
    );
545
546
547
    int response = dlg.ShowModal();
548
    if (response != wxID_OK) {
549
       notifyToUser(_("Canceled by the user"));
550
       exit(1);
551
    }
552
    wxFileName fileName(dlg.GetPath());
553
554
    fileName.SetFullName("");
555
    fileName.AppendDir("..");
556
    fileName.Normalize();
557
    return calculateJavaExePath(fileName.GetPath());
558
559
}
560
561
562
wxString LauncherApp::getJavaExeFileVersion(wxString javaFileName) {
563
        wxArrayString output, errors;
564
        wxString cmd =javaFileName + " GetJavaSystemProperties java.version";
565
        //echo(cmd);
566
        if (!run_external_withOut(cmd,output, errors)) {
567
                return "";
568
        }
569
        if (output.Count() == 0){
570
                return "";
571
        }
572
        return output[0];
573
574
}
575
576
wxString LauncherApp::getJavaExeFileHome(wxString javaFileName) {
577
        wxArrayString output, errors;
578
        wxString cmd =javaFileName + " GetJavaSystemProperties java.home";
579
        if (!run_external_withOut(cmd,output, errors)) {
580
                return "";
581
        }
582
        if (output.Count() == 0){
583
                return "";
584
        }
585
        return output[0];
586
587
}
588
589
590
wxString LauncherApp::checkJava(const wxString aJavaFileName) {
591
        wxString msg = "";
592
        wxString version;
593
        wxString home;
594
595
596
        if (!wxFileExists(aJavaFileName)){
597
                return wxString::Format(_("File %s not found."),aJavaFileName.c_str());//_("File %s not found."), javaFileName);
598
        };
599
600
601
        version = getJavaExeFileVersion(aJavaFileName);
602
603
        if (version.Cmp("") == 0){
604
                return wxString::Format(_("Can't identify version of %s."), aJavaFileName.c_str());
605
        }
606
607
        version = version.Left(5);
608
        if (!compareVersions(version,paramsJreVersion)) {
609
                msg = "\n" + wxString::Format(_("Java version %s is not the required %s"),version.c_str(),paramsJreVersion.c_str());
610
        }
611
612
        home = getJavaExeFileHome(aJavaFileName);
613
        if (home.Cmp("") == 0){
614
                return wxString::Format(_("Can't identify java_home of %s."), aJavaFileName.c_str());
615
        }
616
        // comprobamos JAI
617
        if (!checksJai(home)) {
618
                msg = msg +"\n" + _("The JAI library is not installed");
619
        }
620
        // comprobamos JAI i/o
621
        if (!checksJaiIo(home)) {
622
                msg = msg +"\n" + _("The JAI I/O library is not installed");
623
        }
624
625
        return msg;
626
}
627
628
bool LauncherApp::checkEnvironmentJRE() {
629
        return (useEnvironJRE().Cmp("") != 0);
630
}
631
632
wxString  LauncherApp::useEnvironJRE() {
633
  wxString version("");
634
635
  // Windows[tm] registry lookup
636
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
637
                     "\\Java Runtime Environment\\";
638
639
  wxRegKey bKey(baseKey);
640
  if (!bKey.Exists())  {
641
     return "";
642
  }
643
644
  if (!bKey.QueryValue("CurrentVersion", version)){
645
     return "";
646
  }
647
648
649
  if (version == "") {
650
     return "";
651
  }
652
  wxRegKey vKey(baseKey + version);
653
  wxString theJavaHome;
654
655
  if (!vKey.QueryValue("JavaHome", theJavaHome)){
656
     return "";
657
  }
658
659
660
  return calculateJavaExePath(theJavaHome);
661
662
}
663
664
665
bool LauncherApp::checkPreviousJRE() {
666
        wxFileName appHomeJre = wxString(parseString(paramsProvidedJreInstalledRootDirectory));
667
668
        //echo(appHomeJre.GetFullPath());
669
        appHomeJre.MakeAbsolute();
670
        //echo(appHomeJre.GetFullPath());
671
        appHomeJre.Normalize();
672
673
        //echo(appHomeJre.GetFullPath());
674
675
        if (!appHomeJre.DirExists())  {
676
                return false;
677
        }
678
679
680
        return (!wxFindFirstFile(appHomeJre.GetFullPath()+"/"+paramsJreVersion+"*",wxDIR).IsEmpty());
681
}
682
683
wxString  LauncherApp::previousJRE() {
684
        wxString root(parseString(paramsProvidedJreInstalledRootDirectory));
685
        if (paramsJreVersionPrefered.IsEmpty()) {
686
                wxFileName prefered = calculateJavaExePath(root+"/"+paramsJreVersionPrefered);
687
                prefered.Normalize();
688
                if (prefered.FileExists()){
689
                        return prefered.GetFullPath();
690
                }
691
        }
692
        wxString mask = calculateJavaExePath(root+"/" + paramsJreVersion + "_%02d");
693
        for(unsigned i=20;i>1;i--) {
694
                wxFileName current;
695
                current = wxString::Format(mask,i);
696
                current.Normalize();
697
                if (current.FileExists()) {
698
                        return current.GetFullPath();
699
                }
700
        }
701
        return "";
702
}
703
704
705
wxString LauncherApp::readPathFromINI(wxString section, wxString key, const wxString defaultValue){
706
        char* charResult;
707
708
        charResult =myGetPrivateProfileString(section.c_str(),key.c_str(),defaultValue.c_str(),cfgName.c_str());
709
710
        //Remplazamos \ por /
711
712
        register char* s = charResult;
713
        for (;*s;s++) {
714
                if (*s == '\\') {
715
                        *s = '/';
716
                }
717
        }
718
719
        wxString result(charResult);
720
        return result;
721
722
723
}
724
725
726
727
wxString LauncherApp::readPathFromINI(wxString key, const wxString defaultValue){
728
        return readPathFromINI("default",key,defaultValue);
729
730
}
731
732
wxString LauncherApp::readFromINI(wxString section, wxString key, const wxString defaultValue){
733
        char* charResult;
734
735
        charResult =myGetPrivateProfileString(section.c_str(),key.c_str(),defaultValue.c_str(),cfgName.c_str());
736
737
        wxString result(charResult);
738
        return result;
739
}
740
741
wxString LauncherApp::readFromINI(wxString key, const wxString defaultValue){
742
        return readFromINI("default",key,defaultValue);
743
}
744
745
wxArrayString LauncherApp::sectionKeysFromINI(const wxString section){
746
        char* charResult;
747
748
        charResult =myGetPrivateProfileString(section.c_str(),NULL,NULL,cfgName.c_str());
749
        //echo(section +" = "+charResult);
750
751
        wxArrayString rvalue;
752
        char* token;
753
754
        for (
755
                token = strtok(charResult,"=");
756
                token;
757
                token = strtok(NULL,"=")
758
759
            ) {
760
                rvalue.Add(token);
761
        }
762
        return rvalue;
763
}
764
765
766
wxArrayString LauncherApp::sectionKeysValuesFromINI(const wxString section,wxArrayString keys) {
767
        wxArrayString rvalue;
768
        unsigned int i;
769
        wxString key;
770
        wxString value;
771
        for (i=0;i < keys.GetCount(); i++){
772
                rvalue.Add(readPathFromINI( section, keys[i], ""));
773
        }
774
        return rvalue;
775
}
776
777
778
779
780
781
bool LauncherApp::copyRequiredFiles(){
782
  int i = 0;
783
  //wxFileInputStream in( cfgName );
784
  //wxFileConfig cfg( in );
785
  //cfg.SetPath("/CopyRequiredFiles");
786
787
  wxString source;
788
  wxString target;
789
  wxString msg;
790
  wxFileName fileName;
791
792
  while (true) {
793
        i++;
794
795
        source = readPathFromINI("CopyRequiredFiles",source.Format("source%i",i),wxEmptyString);
796
        target = readPathFromINI("CopyRequiredFiles",target.Format("target%i",i),wxEmptyString);
797
        if (source == wxEmptyString && target == wxEmptyString) {
798
                return true;
799
        }
800
        if (source == wxEmptyString || target == wxEmptyString) {
801
                error(source.Format(_("Error copying the file number %i:\n missing source or target entry"),i));
802
                return false;
803
        }
804
        //source = parseString(source);
805
        //target = parseString(target);
806
        if (wxFileExists(target)){
807
                continue;
808
        } else {
809
            if (wxDirExists(target)) {
810
                fileName = wxFileName(target);
811
                fileName.Normalize();
812
                wxFileName tempFileName(source);
813
                tempFileName.Normalize();
814
                fileName.SetFullName(tempFileName.GetFullName());
815
                if (fileName.FileExists()) {
816
                        continue;
817
                }
818
            }
819
820
        }
821
        if (!wxFileExists(source)){
822
                error(source.Format(_("Error copying the file number %i:\n source file '%s' does not exists."),i,source.c_str()));
823
                return false;
824
        }
825
826
        fileName = wxFileName(source);
827
        fileName.Normalize();
828
        msg = msg.Format(_("copying %s..."), fileName.GetFullName().c_str());
829
        //echo(msg);
830
        //echo(msg.Format("%s --> %s",source.c_str(),target.c_str()));
831
        if (!copyFile(source,target, msg)){
832
                error(source.Format(_("Error copying the file number %i:\n '%s' --> '%s'."),i,source.c_str(),target.c_str()));
833
                return false;
834
        }
835
836
  }
837
}
838
839
bool LauncherApp::copyFile(const wxString source, const wxString target, const wxString msg){
840
841
  bool isOk;
842
  //echo(source);
843
  if (source == wxEmptyString) {
844
     return false;
845
  }
846
847
  //echo(target);
848
  if (target == wxEmptyString) {
849
     return false;
850
  }
851
852
  showStatusMsg(msg);
853
854
  wxFileName targetFileName(target);
855
  targetFileName.Normalize();
856
857
858
  // Preparamos la ruta para el fichero destino
859
  wxArrayString dirs;
860
861
  dirs = targetFileName.GetDirs();
862
  wxString dir;
863
  wxFileName curDir;
864
  curDir.Normalize();
865
  if (targetFileName.IsAbsolute()) {
866
        curDir.Assign("\\");
867
        curDir.SetVolume(targetFileName.GetVolume());
868
  }else{
869
        curDir.Assign(".");
870
  }
871
  for (size_t i=0; i < dirs.GetCount(); i++) {
872
      dir = dirs.Item(i);
873
      curDir.AppendDir(dir);
874
      curDir.Normalize();
875
      //echo("dir " + curDir.GetPath());
876
      if (!curDir.DirExists()) {
877
         //echo("creating dir");
878
         isOk = curDir.Mkdir();
879
         if (!isOk) {
880
            //echo("dir create no ok");
881
            return false;
882
         }
883
884
         //echo("dir create ok");
885
      }
886
  }
887
888
  wxString finalTarget;
889
  if (targetFileName.IsDir() || targetFileName.DirExists()) {
890
      //echo("targetFileName.IsDir -> true  " + targetFileName.GetFullPath());
891
      wxFileName sourceFileName(source);
892
      sourceFileName.Normalize();
893
      targetFileName.SetFullName(sourceFileName.GetFullName());
894
      finalTarget = targetFileName.GetFullPath();
895
  } else {
896
      //echo("targetFileName.IsDir -> false  " + targetFileName.GetFullPath());
897
      finalTarget = target;
898
  }
899
900
901
  //echo(msg.Format("%s --> %s",source.c_str(),finalTarget.c_str()));
902
  isOk = wxCopyFile(source,finalTarget,false);
903
904
905
  return isOk;
906
907
}
908
909
910
911
void LauncherApp::showStatusWindow(){
912
  if (isStatusDialogVisible) {
913
    return;
914
  }
915
916
  statusDialog = new StatusDialog( APPLICATION_NAME );
917
918
  statusDialog->Centre();
919
  statusDialog->Show(TRUE);
920
  isStatusDialogVisible = true;
921
}
922
923
924
925
wxString LauncherApp::parseCommand(){
926
927
  return parseString(paramsCommand);
928
}
929
930
wxString LauncherApp::parseString(const wxString theString){
931
  //echo("IN: " +theString);
932
  wxString resultCommand(theString);
933
934
  // #JAVA#
935
  resultCommand.Replace("#JAVA#",javaExePath.c_str());
936
937
  // #JAVA_HOME#
938
  resultCommand.Replace("#JAVA_HOME#",javaHome.c_str());
939
940
  // #JAR#
941
  resultCommand.Replace("#JAR#",paramsJar.c_str());
942
943
  // calculamos la cadena args y sustituimos los #ARG?#
944
  wxString theArgs("");
945
  wxString theArg("");
946
  int i;
947
  for (i=1;i<this->argc;i++) {
948
    theArg = argv[i];
949
    if (i!=1){
950
            theArgs = theArgs + " \"" + theArg + "\"";
951
    }else{
952
            theArgs = "\"" + theArg + "\"";
953
    }
954
955
    resultCommand.Replace(theArg.Format("\"#ARG%i#\"",i),theArg.c_str());
956
  }
957
  // Dejamos a blanco los argumento que no hemos recivido y existen en el comando
958
  theArg = "";
959
  for (i=i;i<10;i++) {
960
    resultCommand.Replace(theArg.Format("#ARG%i#",i),theArg.c_str());
961
  }
962
  //echo(theArgs);
963
964
  // #ARGS#
965
  resultCommand.Replace("#ARGS#",theArgs.c_str());
966
967
  // #ARG0#
968
  resultCommand.Replace("#ARG0#",argv[0]);
969
970
  // variables de la seccion variables
971
972
  //echo(resultCommand);
973
974
//
975
  if (!variables.IsEmpty()){
976
          //echo(theArg.Format("No empty: count =%i",keys.GetCount()));
977
          unsigned int i;
978
          for (i=0;i<variables.GetCount();i++){
979
                  //echo("#"+variables[i]+"#="+variablesValues[i]);
980
                  resultCommand.Replace("#"+variables[i]+"#",variablesValues[i]);
981
          }
982
983
  //echo(resultCommand);
984
985
  }
986
987
988
  //Despejamos las variables de sistema (WINDOWS)
989
  //
990
  //De momento solo algunas
991
992
  wxString var;
993
  wxGetEnv("windir",&var);
994
  resultCommand.Replace("%windir%",var);
995
996
  wxGetEnv("USERPROFILE",&var);
997
  resultCommand.Replace("%USERPROFILE%",var);
998
999
  wxGetEnv("USERNAME",&var);
1000
  resultCommand.Replace("%USERNAME%",var);
1001
1002
  wxGetEnv("TEMP",&var);
1003
  resultCommand.Replace("%TEMP%",var);
1004
1005
  wxGetEnv("TMP",&var);
1006
  resultCommand.Replace("%TMP%",var);
1007
1008
  wxGetEnv("ProgramFiles",&var);
1009
  resultCommand.Replace("%ProgramFiles%",var);
1010
1011
  wxGetEnv("SystemRoot",&var);
1012
  resultCommand.Replace("%SystemRoot%",var);
1013
1014
1015
  //echo("OUT: " +resultCommand);
1016
  return resultCommand;
1017
}
1018
1019
wxString LauncherApp::calculateJavaExePath(const wxString aJavaHome){
1020
  int osVerMayor;
1021
  int osVerMinor;
1022
1023
  wxGetOsVersion(&osVerMayor,&osVerMinor);
1024
  if (osVerMayor < 5) {
1025
    return aJavaHome + "/bin/java.exe";
1026
  }else{
1027
    return aJavaHome + "/bin/javaw.exe";
1028
  }
1029
1030
}
1031
1032
wxString LauncherApp::searchJRE()
1033
{
1034
  showStatusMsg(_("Searching JRE's..."));
1035
  wxString version("");
1036
1037
  // Windows[tm] registry lookup
1038
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
1039
                     "\\Java Runtime Environment\\";
1040
1041
  wxRegKey bKey(baseKey);
1042
  if (!bKey.Exists())  {
1043
     return "";
1044
  }
1045
1046
  if (!bKey.QueryValue("CurrentVersion", version)){
1047
     return "";
1048
  }
1049
1050
  if (version == "1.1") {
1051
     return "";
1052
  }
1053
1054
  if (!compareVersions(version, paramsJreVersionPrefered)){
1055
        //Nos recorremos las versiones instaladas
1056
        version = "";
1057
        wxString strTemp;
1058
        wxRegKey sKey(baseKey);
1059
        if (sKey.HasSubKey(paramsJreVersionPrefered)) {
1060
      version = wxString(paramsJreVersionPrefered);
1061
    } else {
1062
          for(unsigned i=20;i>1;i--) {
1063
        strTemp = wxString::Format(paramsJreVersion + "_%02d",i);
1064
        if (sKey.HasSubKey(strTemp)) {
1065
                        version = strTemp;
1066
                        break;
1067
                }
1068
          }
1069
    }
1070
  }
1071
1072
1073
  if (version == "") {
1074
     return "";
1075
  }
1076
  return version;
1077
1078
1079
1080
}
1081
1082
wxString LauncherApp::getJavaHomeFromVersion(const wxString aVersion){
1083
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
1084
                     "\\Java Runtime Environment\\";
1085
  wxRegKey vKey(baseKey + aVersion);
1086
  wxString theJavaHome;
1087
1088
  if (!vKey.QueryValue("JavaHome", theJavaHome)){
1089
     return "";
1090
  }
1091
1092
  return theJavaHome;
1093
1094
}
1095
1096
wxString LauncherApp::installJRE(){
1097
1098
  wxString localVersion = searchJRE();
1099
1100
  if (localVersion.Cmp("")!=0){
1101
      jreInstall();
1102
      localVersion = searchJRE();
1103
  }
1104
1105
  wxString theJavaHome = getJavaHomeFromVersion(localVersion);
1106
1107
1108
  fixSystemJREConfig(localVersion);
1109
1110
  jaiInstall(theJavaHome,localVersion);
1111
1112
  jaiIoInstall(theJavaHome,localVersion);
1113
1114
  return calculateJavaExePath(theJavaHome);
1115
}
1116
1117
1118
1119
void LauncherApp::jreInstall()
1120
{
1121
  showStatusWindow();
1122
1123
  showStatusMsg(_("Preparing to install JRE..."));
1124
1125
  if (!checkInstallerFile(paramsJre, paramsJreDownload,_("Java JRE version ")+paramsJreVersion))
1126
  {
1127
    error(_("The JRE could not be setup."));
1128
  }
1129
1130
  showStatusMsg(_("Installing JRE..."));
1131
  if (!run_external(paramsJre))
1132
  {
1133
    error(_("The JRE could not be setup."));
1134
  }
1135
  if (!searchJRE()) {
1136
    error(_("The JRE could not be setup."));
1137
  }
1138
}
1139
1140
1141
void LauncherApp::fixSystemJREConfig(const wxString aVersionToUse){
1142
  showStatusMsg(_("Updating the system..."));
1143
  //actualizamos CurrentVersion
1144
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
1145
                     "\\Java Runtime Environment\\";
1146
1147
  wxString genericVersion = paramsJreVersion.Left(3);
1148
1149
  wxString baseKeyGeneric = baseKey + genericVersion + "\\";
1150
  wxString baseKeyVersion = baseKey + aVersionToUse + "\\";
1151
1152
  wxRegKey *pRegKey = new wxRegKey(baseKey);
1153
  if( !pRegKey->Exists() ) {
1154
    error(_("JRE not found."));
1155
  }
1156
1157
  // compiamos el contenido de la rama de la version
1158
  // que queremos a la generica (1.4 o 1.5 o ...)
1159
  wxRegKey *pRegKeyGeneric = new wxRegKey(baseKeyGeneric);
1160
  wxRegKey *pRegKeyVersion = new wxRegKey(baseKeyVersion);
1161
1162
  if ( !pRegKeyGeneric->Exists() ){
1163
    pRegKeyGeneric->Create();
1164
  }
1165
  wxString tempKey;
1166
  wxString tempValue;
1167
  size_t nValues;
1168
1169
  pRegKeyVersion->GetKeyInfo(NULL,NULL,&nValues,NULL);
1170
  long pos = 1;
1171
  pRegKeyVersion->GetFirstValue(tempKey,pos);
1172
  for(unsigned i=0;i<nValues;i++)        {
1173
      //echo("copy " + tempKey);
1174
      pRegKeyVersion->QueryValue(tempKey,tempValue);
1175
      pRegKeyGeneric->SetValue(tempKey,tempValue);
1176
      pRegKeyVersion->GetNextValue(tempKey,pos);
1177
  }
1178
1179
1180
}
1181
1182
bool LauncherApp::checksJai(const wxString aJavaHome){
1183
   return (wxFileExists(aJavaHome + "\\lib\\ext\\jai_core.jar"));
1184
}
1185
1186
bool LauncherApp::checksJaiIo(const wxString aJavaHome){
1187
   return (wxFileExists(aJavaHome + "\\lib\\ext\\jai_imageio.jar"));
1188
}
1189
1190
void LauncherApp::jaiInstall(const wxString aJavaHome, const wxString aVersionToUse)
1191
{
1192
  bool isOK;
1193
  showStatusMsg(_("Checking JAI Library..."));
1194
1195
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
1196
                     "\\Java Runtime Environment\\";
1197
1198
  wxString currentVersion;
1199
  wxRegKey *pRegKey = new wxRegKey(baseKey);
1200
  if( !pRegKey->Exists() )
1201
    error(_("JRE not found."));
1202
  if (!pRegKey->QueryValue("CurrentVersion", currentVersion)) error(_("JRE not found."));
1203
1204
  isOK=true;
1205
  if (!checksJai(aJavaHome)) {
1206
      //confirm(_("JAI library is required, Install it?"));
1207
      showStatusWindow();
1208
1209
      showStatusMsg(_("Preparing to install JAI Library..."));
1210
      if (!checkInstallerFile(paramsJai, paramsJaiDownload, _("JAI Library")))
1211
      {
1212
        isOK=false;
1213
      } else {
1214
        pRegKey->SetValue("CurrentVersion",aVersionToUse);
1215
        showStatusMsg(_("Preparing to install JAI Library..."));
1216
        if (run_external(paramsJai))
1217
        {
1218
          isOK=(checksJai(aJavaHome));
1219
        } else {
1220
          isOK=false;
1221
        }
1222
        pRegKey->SetValue("CurrentVersion",currentVersion);
1223
      }
1224
1225
  }
1226
  if (!isOK) {
1227
    error(_("The JAI could not be setup."));
1228
  }
1229
}
1230
1231
1232
1233
void LauncherApp::jaiIoInstall(const wxString aJavaHome, const wxString aVersionToUse)
1234
{
1235
  bool isOK;
1236
  showStatusMsg(_("Checking JAI imageIO Library..."));
1237
1238
  wxString baseKey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft"
1239
                     "\\Java Runtime Environment\\";
1240
1241
  wxString currentVersion;
1242
  wxRegKey *pRegKey = new wxRegKey(baseKey);
1243
  if( !pRegKey->Exists() )
1244
    error(_("JRE not found."));
1245
  if (!pRegKey->QueryValue("CurrentVersion", currentVersion)) error(_("JRE not found."));
1246
1247
1248
  isOK=true;
1249
  if (!checksJaiIo(aJavaHome)) {
1250
      //confirm(_("JAI ImageIO library is required, Install it?"));
1251
      showStatusWindow();
1252
1253
      showStatusMsg(_("Preparing to install JAI imageIO Library..."));
1254
      if (!checkInstallerFile(paramsJaiIo, paramsJaiIoDownload,"JAI ImageIO Library"))
1255
      {
1256
        isOK=false;
1257
      } else {
1258
        pRegKey->SetValue("CurrentVersion",aVersionToUse);
1259
        showStatusMsg(_("Installing JAI imageIO Library..."));
1260
        if (run_external(paramsJaiIo))
1261
        {
1262
          isOK=(checksJaiIo(aJavaHome));
1263
        } else {
1264
          isOK=false;
1265
        }
1266
         pRegKey->SetValue("CurrentVersion",currentVersion);
1267
      }
1268
1269
  }
1270
  if (!isOK) {
1271
             error(_("The JAI imageIO could not be setup."));
1272
  }
1273
}
1274
1275
1276
void LauncherApp::showSelectionDialog(){
1277
  bool ok = false;
1278
1279
  wxString mJavaFileName;
1280
  wxString errorMsg;
1281
  SelectionDialog  dlg( checkPreviousJRE(),checkEnvironmentJRE() ,_(APPLICATION_NAME));
1282
  while (!ok) {
1283
        if (dlg.ShowModal() != wxID_OK){
1284
                notifyToUser(_("Canceled by the user"));
1285
                exit(1);
1286
        }
1287
        switch (dlg.getUserAction())
1288
        {
1289
                case PREVIOUS_GVSIG:  mJavaFileName = previousJRE(); break;
1290
                case PROVIDED: mJavaFileName = installProvidedJRE(); break;
1291
                case INSTALL: mJavaFileName = installJRE(); break;
1292
                case SELECT_MANUALY: mJavaFileName = selectJavaExeFileManualy();  break;
1293
                case ENVIRON: mJavaFileName = useEnvironJRE(); break;
1294
                default: break;
1295
        }
1296
        if (mJavaFileName.Cmp("") == 0) {
1297
                wxString msg =wxString::Format(_("Error executing this installation option. Do you want to try another one?"),errorMsg.c_str());
1298
                confirm(msg);
1299
        } else {
1300
                //echo("checking..." + mJavaFileName);
1301
                errorMsg = checkJava(mJavaFileName);
1302
                //echo("check result: *"+errorMsg+"*");
1303
                if (errorMsg.Cmp("") == 0) {
1304
                        setJavaExePath(mJavaFileName);
1305
                        ok=true;
1306
                } else {
1307
                        wxString msg =wxString::Format(_("Problems found in the selected JRE:\n%s\n\nDo you want to continue?"),errorMsg.c_str());
1308
                        if (confirmYesNoCancel(msg,false)) {
1309
                                setJavaExePath(mJavaFileName);
1310
                                ok=true;
1311
                        }
1312
                }
1313
        }
1314
  }
1315
1316
}
1317
1318
void LauncherApp::setJavaExePath(const wxString aJavaExePath){
1319
        javaExePath = aJavaExePath;
1320
        javaHome = getJavaExeFileHome(aJavaExePath);
1321
1322
}