OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-3.0/] [host/] [tools/] [configtool/] [standalone/] [wxwin/] [configtool.cpp] - Blame information for rev 790

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 786 skrzyp
// ####ECOSHOSTGPLCOPYRIGHTBEGIN####                                        
2
// -------------------------------------------                              
3
// This file is part of the eCos host tools.                                
4
// Copyright (C) 1998, 1999, 2000, 2003, 2004, 2005, 2006, 2008, 2009, 2011 Free Software Foundation, Inc.
5
//
6
// This program is free software; you can redistribute it and/or modify     
7
// it under the terms of the GNU General Public License as published by     
8
// the Free Software Foundation; either version 2 or (at your option) any   
9
// later version.                                                           
10
//
11
// This program is distributed in the hope that it will be useful, but      
12
// WITHOUT ANY WARRANTY; without even the implied warranty of               
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        
14
// General Public License for more details.                                 
15
//
16
// You should have received a copy of the GNU General Public License        
17
// along with this program; if not, write to the                            
18
// Free Software Foundation, Inc., 51 Franklin Street,                      
19
// Fifth Floor, Boston, MA  02110-1301, USA.                                
20
// -------------------------------------------                              
21
// ####ECOSHOSTGPLCOPYRIGHTEND####                                          
22
// configtool.cpp :
23
//
24
//===========================================================================
25
//#####DESCRIPTIONBEGIN####
26
//
27
// Author(s):   julians, jld
28
// Contact(s):  julians, jld
29
// Date:        2000/08/24
30
// Version:     $Id: configtool.cpp,v 1.51 2001/12/11 15:59:51 julians Exp $
31
// Purpose:
32
// Description: Implementation file for the ConfigTool application class
33
// Requires:
34
// Provides:
35
// See also:
36
// Known bugs:
37
// Usage:
38
//
39
//####DESCRIPTIONEND####
40
//
41
//===========================================================================
42
 
43
// ============================================================================
44
// declarations
45
// ============================================================================
46
 
47
// ----------------------------------------------------------------------------
48
// headers
49
// ----------------------------------------------------------------------------
50
#ifdef __GNUG__
51
    #pragma implementation "configtool.h"
52
#endif
53
 
54
// Includes other headers for precompiled compilation
55
#include "ecpch.h"
56
 
57
#ifdef __BORLANDC__
58
    #pragma hdrstop
59
#endif
60
 
61
#include "eCosSocket.h"
62
#include "eCosTestPlatform.h"
63
 
64
#include "wx/splash.h"
65
#include "wx/cshelp.h"
66
#include "wx/image.h"
67
#include "wx/filesys.h"
68
#include "wx/fs_zip.h"
69
#include "wx/config.h"
70
#include "wx/cmdline.h"
71
#include "wx/process.h"
72
#include "wx/mimetype.h"
73
#include "wx/txtstrm.h"
74
#include "wx/wfstream.h"
75
#include "wx/fs_mem.h"
76
 
77
#include "configtool.h"
78
#include "configtoolview.h"
79
#include "configtree.h"
80
#include "mainwin.h"
81
#include "outputwin.h"
82
#include "configtooldoc.h"
83
#include "aboutdlg.h"
84
#include "shortdescrwin.h"
85
#include "conflictwin.h"
86
#include "propertywin.h"
87
#include "symbols.h"
88
#include "build.hxx"
89
#include "Subprocess.h"
90
 
91
// ----------------------------------------------------------------------------
92
// resources
93
// ----------------------------------------------------------------------------
94
// the application icon
95
#if defined(__WXGTK__) || defined(__WXMOTIF__)
96
    #include "bitmaps/configtool.xpm"
97
#endif
98
 
99
// Create a new application object.
100
IMPLEMENT_APP(ecApp)
101
 
102
BEGIN_EVENT_TABLE(ecApp, wxApp)
103
// Don't handle automatically, or it will bypass more specific processing.
104
//    EVT_MENU(ecID_WHATS_THIS, ecApp::OnWhatsThis)
105
END_EVENT_TABLE()
106
 
107
bool ecApp::sm_arMounted[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
108
 
109
static const wxCmdLineEntryDesc sg_cmdLineDesc[] =
110
{
111
/*
112
    { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
113
    { wxCMD_LINE_SWITCH, "q", "quiet",   "be quiet" },
114
 
115
    { wxCMD_LINE_OPTION, "o", "output",  "output file" },
116
    { wxCMD_LINE_OPTION, "i", "input",   "input dir" },
117
    { wxCMD_LINE_OPTION, "s", "size",    "output block size", wxCMD_LINE_VAL_NUMBER },
118
    { wxCMD_LINE_OPTION, "d", "date",    "output file date", wxCMD_LINE_VAL_DATE },
119
*/
120
    { wxCMD_LINE_SWITCH, "h", "help",   "displays help on the command line parameters" },
121
    { wxCMD_LINE_SWITCH, "e", "edit-only",    "edit save file only" },
122
    { wxCMD_LINE_SWITCH, "v", "version",    "print version" },
123
    { wxCMD_LINE_SWITCH, "c", "compile-help",    "compile online help only" },
124
 
125
    { wxCMD_LINE_PARAM,  NULL, NULL, "input file 1", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
126
    { wxCMD_LINE_PARAM,  NULL, NULL, "input file 2", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
127
 
128
    { wxCMD_LINE_NONE }
129
};
130
 
131
ecApp::ecApp()
132
{
133
    m_docManager = NULL;
134
    m_mainFrame = NULL;
135
    m_currentDoc = NULL;
136
    m_helpFile = wxEmptyString;
137
    m_splashScreen = NULL;
138
    m_pipedProcess = NULL;
139
    m_valuesLocked = 0;
140
    m_helpController = NULL;
141
}
142
 
143
ecApp::~ecApp()
144
{
145
    delete m_whatsThisMenu;
146
    delete m_fileSystem;
147
}
148
 
149
// 'Main program' equivalent: the program execution "starts" here
150
bool ecApp::OnInit()
151
{
152
// workaround for an exception handling issue with Cygwin 1.5.20
153
#ifdef __CYGWIN__
154
    try {
155
        throw int(42);
156
    } catch(...) { };
157
#endif
158
 
159
    // Mandatory initialisation for Tcl 8.4
160
    Tcl_FindExecutable(argv[0]);
161
 
162
    wxLog::SetTimestamp(NULL);
163
 
164
    m_whatsThisMenu = new wxMenu;
165
    m_whatsThisMenu->Append(ecID_WHATS_THIS, _("&What's This?"));
166
 
167
    m_fileSystem = new wxFileSystem;
168
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
169
    m_zipHandler = new wxZipFSHandler;
170
#endif
171
 
172
    wxHelpProvider::Set(new wxSimpleHelpProvider);
173
    //wxHelpProvider::Set(new wxHelpControllerHelpProvider(& m_helpController));
174
 
175
    wxImage::AddHandler(new wxPNGHandler);
176
    wxImage::AddHandler(new wxGIFHandler);
177
 
178
    // Required for advanced HTML help
179
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
180
    wxFileSystem::AddHandler(m_zipHandler);
181
#endif
182
 
183
    wxString currentDir = wxGetCwd();
184
 
185
    // Use argv to get current app directory
186
    m_appDir = wxFindAppPath(argv[0], currentDir, wxT("CONFIGTOOLDIR"));
187
 
188
    // If the development version, go up a directory.
189
#ifdef __WXMSW__
190
    if ((m_appDir.Right(5).CmpNoCase("DEBUG") == 0) ||
191
        (m_appDir.Right(11).CmpNoCase("DEBUGSTABLE") == 0) ||
192
        (m_appDir.Right(7).CmpNoCase("RELEASE") == 0) ||
193
        (m_appDir.Right(13).CmpNoCase("RELEASESTABLE") == 0)
194
        )
195
        m_appDir = wxPathOnly(m_appDir);
196
#endif
197
 
198
// Install default platform definitions if no platforms defined
199
#ifdef __WXMSW__
200
    wxConfig config (wxGetApp().GetSettings().GetConfigAppName());
201
    if (! config.Exists (wxT("Platforms")))
202
    {
203
        wxFileName platforms (m_appDir, wxT("platforms.reg"));
204
        platforms.Normalize();
205
        if (platforms.FileExists())
206
            wxExecute (wxT("regedit /s \"") + platforms.GetFullPath() + wxT("\""), wxEXEC_SYNC);
207
    }
208
#endif
209
#ifdef __WXGTK__
210
    wxFileName config (wxFileName::GetHomeDir(), wxEmptyString);
211
    config.AppendDir(wxT(".eCosPlatforms"));
212
    if (! config.DirExists())
213
    {
214
        wxFileName platforms (m_appDir, wxT("platforms.tar"));
215
        platforms.Normalize();
216
        if (platforms.FileExists())
217
            wxExecute (wxT("tar -C ") + wxFileName::GetHomeDir() + wxT(" -xf ") + platforms.GetFullPath(), wxEXEC_SYNC);
218
    }
219
#endif
220
 
221
    CeCosSocket::Init();
222
    CeCosTestPlatform::Load();
223
 
224
    // Load resources from binary resources archive, or failing that, from
225
    // Windows resources or plain files
226
    LoadResources();
227
 
228
    // remove "tty" from CYGWIN environment variable to allow correct
229
    // execution of cygwin command-line tools from this application
230
#ifdef __WXMSW__
231
    wxString strCygwin = wxGetenv(wxT("CYGWIN"));
232
    strCygwin = wxT(" ") + strCygwin;
233
    strCygwin.Replace(wxT(" tty"), wxEmptyString);
234
    strCygwin.Trim(false);
235
    wxSetEnv(wxT("CYGWIN"), strCygwin);
236
#endif
237
 
238
    wxGetEnv(wxT("PATH"), & m_strOriginalPath);
239
 
240
    // Create a document manager
241
    m_docManager = new wxDocManager;
242
 
243
    // Create a template relating documents to their views
244
    wxDocTemplate* templ = new wxDocTemplate(m_docManager, "Configtool", "*.ecc", "", "ecc", "Configtool Doc", "Configtool View",
245
        CLASSINFO(ecConfigToolDoc), CLASSINFO(ecConfigToolView));
246
 
247
    // If we've only got one window, we only get to edit
248
    // one document at a time.
249
    m_docManager->SetMaxDocsOpen(1);
250
 
251
    // Initialize config settings
252
    m_settings.Init();
253
 
254
    // Let wxWindows know what the app name is
255
    SetAppName(m_settings.GetAppName());
256
 
257
    InitializeWindowSettings(TRUE /* beforeWindowConstruction */) ;
258
 
259
    // Load config settings
260
    m_settings.LoadConfig();
261
 
262
    // Set the default directory for opening/saving files
263
    if (!m_settings.m_lastFilename.IsEmpty())
264
        templ->SetDirectory(wxPathOnly(m_settings.m_lastFilename));
265
 
266
    // Parse the command-line parameters and options
267
    wxCmdLineParser parser(sg_cmdLineDesc, argc, argv);
268
    int res;
269
    {
270
        wxLogNull log;
271
        res = parser.Parse();
272
    }
273
    if (res == -1 || res > 0 || parser.Found(wxT("h")))
274
    {
275
#ifdef __WXGTK__
276
        wxLog::SetActiveTarget(new wxLogStderr);
277
#endif
278
        parser.Usage();
279
        return FALSE;
280
    }
281
    if (parser.Found(wxT("v")))
282
    {
283
#ifdef __WXGTK__
284
        wxLog::SetActiveTarget(new wxLogStderr);
285
#endif
286
        wxString msg;
287
        msg.Printf(wxT("eCos Configuration Tool (c) Free Software Foundation, Inc., 1998-2011 Version %s, %s"), ecCONFIGURATION_TOOL_VERSION, __DATE__);
288
        wxLogMessage(msg);
289
        return FALSE;
290
    }
291
 
292
/*
293
#ifdef __WXMSW__
294
    wxBitmap bitmap(wxBITMAP(splash));
295
#else
296
    wxBitmap bitmap;
297
    if (wxFileExists("splash16.png"))
298
        bitmap.LoadFile("splash16.png", wxBITMAP_TYPE_PNG);
299
#endif
300
*/
301
 
302
    //    wxYieldIfNeeded();
303
 
304
    // create the main application window
305
    ecMainFrame *frame = new ecMainFrame(m_docManager, GetSettings().GetAppName(),
306
        wxPoint(GetSettings().m_frameSize.x, GetSettings().m_frameSize.y),
307
        wxSize(GetSettings().m_frameSize.width, GetSettings().m_frameSize.height));
308
 
309
    m_mainFrame = frame;
310
    SetTopWindow(frame);
311
    frame->Show(TRUE);
312
 
313
#if wxCHECK_VERSION(2, 6, 0)
314
        // Don't do anything for now as the function is only for wxWidgets internal use
315
#else
316
    SendIdleEvents(); // Otherwise UI updates aren't done, because it's busy loading the repository
317
#endif
318
 
319
#ifdef __WXMSW__
320
    ::UpdateWindow((HWND) frame->GetHWND());
321
#endif
322
 
323
    InitializeWindowSettings(FALSE /* beforeWindowConstruction */) ;
324
 
325
    if (m_splashScreenBitmap.Ok() && GetSettings().m_showSplashScreen)
326
    {
327
        m_splashScreen = new ecSplashScreen(m_splashScreenBitmap, wxSPLASH_CENTRE_ON_SCREEN|wxSPLASH_TIMEOUT,
328
            5000, NULL, -1, wxDefaultPosition, wxDefaultSize, wxNO_BORDER|wxFRAME_FLOAT_ON_PARENT|wxSTAY_ON_TOP);
329
    }
330
 
331
    //    if (m_splashScreen)
332
    //        m_splashScreen->Raise();
333
 
334
    wxYieldIfNeeded();
335
 
336
    if (parser.Found(wxT("e")))
337
        GetSettings().m_editSaveFileOnly = TRUE;
338
 
339
    // If in --compile-help (-c) mode, then exit immediately after recompiling help file
340
    bool compileHelpOnly = parser.Found(wxT("c"));
341
 
342
    wxString filenameToOpen1, filenameToOpen2;
343
    if (parser.GetParamCount() > 0)
344
    {
345
        wxString tmpSaveFile;
346
 
347
        filenameToOpen1 = parser.GetParam(0);
348
 
349
        if (parser.GetParamCount() > 1)
350
            filenameToOpen2 = parser.GetParam(1);
351
 
352
        bool gotRepository = FALSE;
353
        bool gotSavefile = FALSE;
354
 
355
        wxString repositoryDir, saveFile;
356
 
357
        // Might be e.g. . or .. in path, or relative path
358
        filenameToOpen1 = wxGetRealPath(currentDir, filenameToOpen1);
359
 
360
        if (parser.GetParamCount() > 1)
361
            filenameToOpen2 = wxGetRealPath(currentDir, filenameToOpen2);
362
 
363
        wxString path1, name1, ext1;
364
        wxSplitPath(filenameToOpen1, & path1, & name1, & ext1);
365
 
366
        wxString path2, name2, ext2;
367
        wxSplitPath(filenameToOpen2, & path2, & name2, & ext2);
368
 
369
        // Look at the first file
370
        if (ext1 == "ecc" || ext1 == "ECC")
371
        {
372
            if (wxFileExists(filenameToOpen1))
373
            {
374
                gotSavefile = TRUE;
375
                saveFile = filenameToOpen1;
376
            }
377
            else
378
            {
379
                wxString msg;
380
                msg.Printf("%s is not a valid file.", (const wxChar*) filenameToOpen1);
381
                wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
382
                return FALSE;
383
            }
384
        }
385
        else if (wxDirExists(filenameToOpen1) && FindSaveFileInDir(filenameToOpen1, tmpSaveFile))
386
        {
387
            saveFile = tmpSaveFile;
388
            gotSavefile = TRUE;
389
        }
390
        else if ((name1 == wxT("ecos") && ext1 == wxT("db") && wxFileExists(filenameToOpen1)) || wxDirExists(filenameToOpen1))
391
        {
392
            // It's a repository (we hope).
393
            if (name1 == wxT("ecos") && ext1 == wxT("db"))
394
            {
395
                // Go two steps up
396
                filenameToOpen1 = wxPathOnly(filenameToOpen1);
397
                filenameToOpen1 = wxPathOnly(filenameToOpen1);
398
            }
399
            else
400
            {
401
                // If it's the packages directory, we need to strip off
402
                // a directory
403
                wxString eccPath(filenameToOpen1 + wxString(wxFILE_SEP_PATH) + wxT("ecc"));
404
 
405
                // Don't strip off ecc if it's the CVS repository (with ecc below it)
406
                if (name1 == wxT("packages") || (name1 == wxT("ecc") && !wxDirExists(eccPath)))
407
                    filenameToOpen1 = wxPathOnly(filenameToOpen1);
408
            }
409
 
410
            repositoryDir = filenameToOpen1;
411
            gotRepository = TRUE;
412
        }
413
        else
414
        {
415
            wxString msg;
416
            msg.Printf("%s is neither a project file nor a valid repository.", (const wxChar*) filenameToOpen1);
417
            wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
418
            return FALSE;
419
        }
420
 
421
        // Look at the second file, if any
422
        if (parser.GetParamCount() > 1)
423
        {
424
            if (ext2 == "ecc" || ext2 == "ECC")
425
            {
426
                if (wxFileExists(filenameToOpen2))
427
                {
428
                    if (gotSavefile)
429
                    {
430
                        wxString msg;
431
                        msg.Printf("%s is a second save file -- please supply only one.", (const wxChar*) filenameToOpen2);
432
                        wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
433
                        return FALSE;
434
                    }
435
 
436
                    gotSavefile = TRUE;
437
                    saveFile = filenameToOpen2;
438
                }
439
                else
440
                {
441
                    wxString msg;
442
                    msg.Printf("%s is not a valid file.", (const wxChar*) filenameToOpen2);
443
                    wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
444
                    return FALSE;
445
                }
446
            }
447
            else if (!gotSavefile && wxDirExists(filenameToOpen2) && FindSaveFileInDir(filenameToOpen2, tmpSaveFile))
448
            {
449
                saveFile = tmpSaveFile;
450
                gotSavefile = TRUE;
451
            }
452
            else if ((name2 == wxT("ecos") && ext2 == wxT("db") && wxFileExists(filenameToOpen2)) || wxDirExists(filenameToOpen2))
453
            {
454
                if (gotRepository)
455
                {
456
                    wxString msg;
457
                    msg.Printf("%s is a second repository -- please supply only one.", (const wxChar*) filenameToOpen2);
458
                    wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
459
                    return FALSE;
460
                }
461
 
462
                // It's a repository (we hope).
463
                if (name1 == wxT("ecos") && ext1 == wxT("db"))
464
                {
465
                    // Go two steps up
466
                    filenameToOpen2 = wxPathOnly(filenameToOpen2);
467
                    filenameToOpen2 = wxPathOnly(filenameToOpen2);
468
                }
469
                else
470
                {
471
                    // If it's the packages directory, we need to strip off
472
                    // a directory
473
                    wxString eccPath(filenameToOpen2 + wxString(wxFILE_SEP_PATH) + wxT("ecc"));
474
 
475
                    // Don't strip off ecc if it's the CVS repository (with ecc below it)
476
                    if (name2 == wxT("packages") || (name2 == wxT("ecc") && !wxDirExists(eccPath)))
477
                        filenameToOpen2 = wxPathOnly(filenameToOpen2);
478
                }
479
 
480
                repositoryDir = filenameToOpen2;
481
                gotRepository = TRUE;
482
            }
483
            else
484
            {
485
                wxString msg;
486
                msg.Printf("%s is neither a project file nor a valid repository.", (const wxChar*) filenameToOpen2);
487
                wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
488
                return FALSE;
489
            }
490
        }
491
 
492
        // Now we have looked at the two files and decided what they are; let's
493
        // act on it.
494
 
495
        if (gotRepository)
496
        {
497
            GetSettings().m_strRepository = repositoryDir;
498
        }
499
 
500
        if (!gotSavefile)
501
        {
502
            // See if there's a save file in the current dir
503
            if (FindSaveFileInDir(currentDir, saveFile))
504
                gotSavefile = TRUE;
505
        }
506
 
507
        if (gotSavefile)
508
        {
509
            // The repository will be loaded from m_strRepository, possibly set above.
510
            m_docManager->CreateDocument(saveFile, wxDOC_SILENT);
511
        }
512
        else
513
        {
514
            // Create a new file
515
            m_docManager->CreateDocument(wxString(""), wxDOC_NEW);
516
        }
517
 
518
        if (compileHelpOnly)
519
        {
520
            if (!gotRepository)
521
            {
522
                wxString msg;
523
                msg.Printf(wxT("Please specify a repository when using the --compile-help option."));
524
                wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
525
                return FALSE;
526
            }
527
            ecConfigToolDoc* doc = wxGetApp().GetConfigToolDoc();
528
            if (doc)
529
            {
530
                if (!doc->RebuildHelpIndex(TRUE))
531
                {
532
                    wxString msg;
533
                    msg.Printf(wxT("Sorry, there was a problem compiling the help index."));
534
                    wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
535
                    return FALSE;
536
                }
537
            }
538
            else
539
            {
540
                wxString msg;
541
                msg.Printf(wxT("Sorry, there was no current document when compiling the help index."));
542
                wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
543
                return FALSE;
544
            }
545
 
546
            // Return FALSE in order to quit the application
547
            return FALSE;
548
        }
549
    }
550
    else
551
    {
552
        if (GetSettings().m_strRepository.IsEmpty() ||
553
            !wxFileName::DirExists(GetSettings().m_strRepository)) // first invocation by this user
554
        {
555
            // we have no clues as to the location of the repository so
556
            // test for ../../packages relative to the configtool location
557
            wxFileName repository = wxFileName (m_appDir, wxEmptyString);
558
            repository.Normalize(); // remove trailing "./" if present
559
            repository.RemoveDir (repository.GetDirCount()-1);
560
            repository.RemoveDir (repository.GetDirCount()-1);
561
            repository.AppendDir (wxT("packages"));
562
            if (repository.DirExists()) // we've found a repository
563
            {
564
                repository.RemoveDir (repository.GetDirCount()-1);
565
                GetSettings().m_strRepository = repository.GetFullPath();
566
            }
567
        }
568
        m_docManager->CreateDocument(wxString(""), wxDOC_NEW);
569
    }
570
 
571
    return TRUE;
572
}
573
 
574
// Load resources from disk
575
bool ecApp::LoadResources()
576
{
577
    wxFileSystem::AddHandler(new wxMemoryFSHandler);
578
 
579
//    LoadBitmapResource(m_splashScreenBitmap, wxT("splash16.png"), wxBITMAP_TYPE_PNG, FALSE);
580
 
581
//    wxBitmap bitmap1, bitmap2, bitmap3;
582
//    LoadBitmapResource(bitmap1, wxT("ecoslogo.png"), wxBITMAP_TYPE_PNG, TRUE);
583
//    LoadBitmapResource(bitmap2, wxT("ecoslogosmall.png"), wxBITMAP_TYPE_PNG, TRUE);
584
//    LoadBitmapResource(bitmap3, wxT("rhlogo.png"), wxBITMAP_TYPE_PNG, TRUE);
585
 
586
//    wxString aboutText;
587
//    LoadTextResource(aboutText, wxT("about.htm"), TRUE);
588
 
589
//    VersionStampSplashScreen();
590
 
591
    return TRUE;
592
}
593
 
594
// Load resources from zip resource file or disk
595
bool ecApp::LoadBitmapResource(wxBitmap& bitmap, const wxString& filename, int bitmapType, bool addToMemoryFS)
596
{
597
    wxString archive(GetFullAppPath(wxT("configtool.bin")));
598
 
599
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
600
    wxFSFile* file = m_fileSystem->OpenFile(archive + wxString(wxT("#zip:")) + filename);
601
    if (file)
602
    {
603
        wxInputStream* stream = file->GetStream();
604
 
605
        wxImage image(* stream, bitmapType);
606
        bitmap = wxBitmap(image);
607
 
608
        delete file;
609
    }
610
#endif
611
 
612
#ifdef __WXMSW__
613
    if (!bitmap.Ok())
614
        bitmap.LoadFile(filename, wxBITMAP_TYPE_BMP_RESOURCE);
615
#endif
616
 
617
    if (!bitmap.Ok() && wxFileExists(GetFullAppPath(filename)))
618
        bitmap.LoadFile(GetFullAppPath(filename), (wxBitmapType) bitmapType);
619
 
620
 
621
    if (bitmap.Ok() && addToMemoryFS)
622
        wxMemoryFSHandler::AddFile(filename, bitmap, bitmapType);
623
 
624
    return bitmap.Ok();
625
}
626
 
627
// Load resources from zip resource file or disk
628
bool ecApp::LoadTextResource(wxString& text, const wxString& filename, bool addToMemoryFS)
629
{
630
    wxString archive(GetFullAppPath(wxT("configtool.bin")));
631
 
632
    bool success = FALSE;
633
 
634
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
635
    wxFSFile* file = m_fileSystem->OpenFile(archive + wxString(wxT("#zip:")) + filename);
636
    if (file)
637
    {
638
        wxInputStream* stream = file->GetStream();
639
 
640
        char* buf = text.GetWriteBuf(stream->GetSize() + 1);
641
        stream->Read((void*) buf, stream->GetSize());
642
        buf[stream->GetSize()] = 0;
643
        text.UngetWriteBuf();
644
 
645
        success = TRUE;
646
 
647
        delete file;
648
    }
649
#endif
650
 
651
    if (!success && wxFileExists(GetFullAppPath(filename)))
652
    {
653
        wxFileInputStream str(GetFullAppPath(filename));
654
 
655
        char* buf = text.GetWriteBuf(str.GetSize() + 1);
656
        str.Read((void*) buf, str.GetSize());
657
        buf[str.GetSize()] = 0;
658
        text.UngetWriteBuf();
659
 
660
        success = TRUE;
661
    }
662
 
663
    if (success && addToMemoryFS)
664
        wxMemoryFSHandler::AddFile(filename, text);
665
 
666
    return success;
667
}
668
 
669
// Get a text resource from the memory filesystem
670
bool ecApp::GetMemoryTextResource(const wxString& filename, wxString& text)
671
{
672
    wxString s(wxString(wxT("memory:")) + filename);
673
    wxFSFile* file = wxGetApp().GetFileSystem()->OpenFile(s);
674
    if (file)
675
    {
676
        wxInputStream* stream = file->GetStream();
677
 
678
        char* buf = text.GetWriteBuf(stream->GetSize() + 1);
679
        stream->Read((void*) buf, stream->GetSize());
680
        buf[stream->GetSize()] = 0;
681
        text.UngetWriteBuf();
682
 
683
        delete file;
684
        return TRUE;
685
    }
686
    else
687
        return FALSE;
688
}
689
 
690
// Version-stamp the splash screen
691
bool ecApp::VersionStampSplashScreen()
692
{
693
    if (m_splashScreenBitmap.Ok())
694
    {
695
        wxMemoryDC dc;
696
        dc.SelectObject(m_splashScreenBitmap);
697
 
698
        wxColour textColour(19, 49, 4);
699
        dc.SetTextForeground(textColour);
700
        dc.SetBackgroundMode(wxTRANSPARENT);
701
        dc.SetFont(wxFont(11, wxSWISS, wxNORMAL, wxBOLD, FALSE));
702
 
703
        // Bottom left of area to start drawing at
704
 
705
        wxString verString;
706
        verString.Printf("%s", ecCONFIGURATION_TOOL_VERSION);
707
 
708
        int x = 339; int y = 231;
709
#ifdef __WXMSW__
710
        y += 5; // For some reason
711
#endif
712
        int w, h;
713
        dc.GetTextExtent(verString, & w, & h);
714
        dc.DrawText(verString, x, y - h);
715
 
716
        dc.SelectObject(wxNullBitmap);
717
 
718
        return TRUE;
719
    }
720
    else
721
        return FALSE;
722
}
723
 
724
// Initialize window settings object
725
bool ecApp::InitializeWindowSettings(bool beforeWindowConstruction)
726
{
727
    wxWindowSettings& settings = GetSettings().m_windowSettings;
728
    ecMainFrame* frame = GetMainFrame();
729
 
730
    if (beforeWindowConstruction)
731
    {
732
        settings.Add(wxT("Configuration"));
733
        settings.Add(wxT("Short Description"));
734
        settings.Add(wxT("Output"));
735
        settings.Add(wxT("Properties"));
736
        settings.Add(wxT("Conflicts"));
737
    }
738
    else
739
    {
740
        wxArrayPtrVoid arr;
741
        arr.Add(frame->GetTreeCtrl());
742
        arr.Add(frame->GetValueWindow());
743
        settings.SetWindows(wxT("Configuration"), arr);
744
 
745
        settings.SetWindow(wxT("Short Description"), frame->GetShortDescriptionWindow());
746
        settings.SetWindow(wxT("Output"), frame->GetOutputWindow());
747
        settings.SetWindow(wxT("Properties"), frame->GetPropertyListWindow());
748
        settings.SetWindow(wxT("Conflicts"), frame->GetConflictsWindow());
749
    }
750
 
751
    return TRUE;
752
}
753
 
754
 
755
bool ecApp::InitializeHelpController()
756
{
757
    if (m_helpController)
758
        delete m_helpController;
759
    m_helpController = new wxHelpController;
760
 
761
    if (!m_helpController->Initialize(GetHelpFile()))
762
    {
763
        // TODO
764
        return FALSE;
765
    }
766
    else
767
    {
768
        // Tell the help controller where the repository documentation is.
769
        // For now, just keep this to myself since it uses hacks to wxWin
770
        ecConfigToolDoc* doc = GetConfigToolDoc();
771
 
772
        // No longer using relative paths
773
#if 0
774
        if (doc)
775
        {
776
            wxString htmlDir = wxString(doc->GetRepository()) + wxString(wxT("/doc/html"));
777
            if (!wxDirExists(htmlDir))
778
                htmlDir = wxString(doc->GetRepository()) + wxString(wxT("/doc"));
779
 
780
            htmlDir += wxString(wxT("/"));
781
 
782
            wxGetApp().GetHelpController().SetBookBasePath(htmlDir);
783
        }
784
#endif
785
        return TRUE;
786
    }
787
}
788
 
789
// Check if there is a (unique) .ecc file in dir
790
bool ecApp::FindSaveFileInDir(const wxString& dir, wxString& saveFile)
791
{
792
    wxDir fileFind;
793
 
794
    if (!fileFind.Open(dir))
795
        return FALSE;
796
 
797
    wxString wildcard = wxT(".ecc");
798
    wxString filename;
799
 
800
    bool found = fileFind.GetFirst (& filename, wildcard);
801
    if (found)
802
    {
803
        // Fail if there was more than one matching file.
804
        wxString filename2;
805
        if (fileFind.GetNext (& filename2))
806
            return FALSE;
807
        else
808
        {
809
            saveFile = dir + wxString(wxFILE_SEP_PATH) + filename;
810
            return TRUE;
811
        }
812
    }
813
    return FALSE;
814
}
815
 
816
int ecApp::OnExit(void)
817
{
818
/*
819
    if (m_helpController)
820
    {
821
        delete m_helpController;
822
        m_helpController = NULL;
823
    }
824
*/
825
 
826
    if (m_splashScreen)
827
    {
828
        m_splashScreen->Destroy();
829
        m_splashScreen = NULL;
830
    }
831
 
832
    m_settings.SaveConfig();
833
 
834
    {
835
        wxConfig config(wxGetApp().GetSettings().GetConfigAppName());
836
        if (config.HasGroup(wxT("FileHistory")))
837
            config.DeleteGroup(wxT("FileHistory"));
838
        config.SetPath(wxT("FileHistory/"));
839
        m_docManager->FileHistorySave(config);
840
    }
841
 
842
    delete m_docManager;
843
 
844
    return 0;
845
}
846
 
847
// Prepend the current program directory to the name
848
wxString ecApp::GetFullAppPath(const wxString& filename) const
849
{
850
    wxString path(m_appDir);
851
    if (path.Last() != '\\' && path.Last() != '/' && filename[0] != '\\' && filename[0] != '/')
852
#ifdef __WXGTK__
853
        path += '/';
854
#else
855
        path += '\\';
856
#endif
857
    path += filename;
858
 
859
    return path;
860
}
861
 
862
// Are we running in 32K colours or more?
863
bool ecApp::GetHiColour() const
864
{
865
    static bool hiColour = (wxDisplayDepth() >= 16) ;
866
    return hiColour;
867
}
868
 
869
// General handler for 'What's this?'
870
void ecApp::OnWhatsThis(wxCommandEvent& event)
871
{
872
    wxObject* obj = event.GetEventObject();
873
    wxWindow* win = NULL;
874
 
875
    if (obj->IsKindOf(CLASSINFO(wxMenu)))
876
    {
877
        win = ((wxMenu*) obj)->GetInvokingWindow();
878
    }
879
    else if (obj->IsKindOf(CLASSINFO(wxWindow)))
880
    {
881
        win = (wxWindow*) obj;
882
    }
883
 
884
    wxWindow* subjectOfHelp = win;
885
    bool eventProcessed = FALSE;
886
    wxPoint pt = wxGetMousePosition();
887
 
888
    while (subjectOfHelp && !eventProcessed)
889
    {
890
        wxHelpEvent helpEvent(wxEVT_HELP, subjectOfHelp->GetId(), pt) ;
891
        helpEvent.SetEventObject(this);
892
        eventProcessed = win->GetEventHandler()->ProcessEvent(helpEvent);
893
 
894
        // Go up the window hierarchy until the event is handled (or not).
895
        // I.e. keep submitting ancestor windows until one is recognised
896
        // by the app code that processes the ids and displays help.
897
        subjectOfHelp = subjectOfHelp->GetParent();
898
    }
899
    // wxGetApp().GetHelpController().DisplayTextPopup(GetHelpText(), wxGetMousePosition());
900
}
901
 
902
// Log to output window
903
void ecApp::Log(const wxString& msg)
904
{
905
    ecMainFrame* frame = (ecMainFrame*) GetTopWindow();
906
    if (frame)
907
    {
908
        frame->GetOutputWindow()->AppendText(msg /* + wxT("\n") */ );
909
        if ((msg == wxEmptyString) || (msg.Last() != wxT('\n')))
910
            frame->GetOutputWindow()->AppendText(wxT("\n"));
911
 
912
#ifdef __CYGWIN__
913
                // Seem to need this under Cygwin to force the last insert point to show
914
                frame->GetOutputWindow()->ShowPosition(frame->GetOutputWindow()->GetLastPosition());
915
#endif
916
    }
917
}
918
 
919
void ecApp::SetStatusText(const wxString& text, bool clearFailingRulesPane)
920
{
921
    ecMainFrame* mainFrame = GetMainFrame();
922
    if(mainFrame)
923
    {
924
        mainFrame->GetStatusBar()->SetStatusText(text, ecStatusPane);
925
        if (clearFailingRulesPane)
926
            mainFrame->GetStatusBar()->SetStatusText(wxT(""), ecFailRulePane);
927
#ifdef __WXMSW__
928
        ::UpdateWindow((HWND) mainFrame->GetHWND());
929
        //wxYield();
930
#endif
931
    }
932
}
933
 
934
// Config tree control
935
ecConfigTreeCtrl* ecApp::GetTreeCtrl() const
936
{
937
    return GetMainFrame()->GetTreeCtrl();
938
}
939
 
940
// MLT window
941
ecMemoryLayoutWindow* ecApp::GetMLTWindow() const
942
{
943
    return GetMainFrame()->GetMemoryLayoutWindow();
944
}
945
 
946
// Get active document
947
ecConfigToolDoc* ecApp::GetConfigToolDoc() const
948
{
949
    if (m_currentDoc)
950
        return m_currentDoc;
951
 
952
    if (!m_docManager)
953
        return NULL;
954
 
955
    return wxDynamicCast(m_docManager->GetCurrentDocument(), ecConfigToolDoc);
956
}
957
 
958
bool ecApp::Launch(const wxString & strFileName,const wxString &strViewer)
959
{
960
    bool ok = FALSE;
961
    wxString cmd;
962
 
963
    if (!strViewer.IsEmpty())
964
    {
965
        cmd = strViewer + wxString(wxT(" ")) + strFileName ;
966
    }
967
    else
968
    {
969
        wxString path, filename, ext;
970
        wxSplitPath(strFileName, & path, & filename, & ext);
971
 
972
        wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
973
        if ( !ft )
974
        {
975
            wxLogError(_T("Impossible to determine the file type for extension '%s'"),
976
                ext.c_str());
977
            return FALSE;
978
        }
979
 
980
        bool ok = ft->GetOpenCommand(&cmd,
981
            wxFileType::MessageParameters(strFileName, _T("")));
982
        delete ft;
983
 
984
        if (!ok)
985
        {
986
            // TODO: some kind of configuration dialog here.
987
            wxMessageBox(_("Could not determine the command for opening this file."),
988
                wxGetApp().GetSettings().GetAppName(), wxOK|wxICON_EXCLAMATION);
989
            return FALSE;
990
        }
991
    }
992
 
993
    ok = (wxExecute(cmd, FALSE) != 0);
994
 
995
    return ok;
996
 
997
#if 0    
998
    bool rc=false;
999
 
1000
    if(!strViewer.IsEmpty())//use custom editor
1001
    {
1002
        CString strCmdline(strViewer);
1003
 
1004
        TCHAR *pszCmdLine=strCmdline.GetBuffer(strCmdline.GetLength());
1005
        GetShortPathName(pszCmdLine,pszCmdLine,strCmdline.GetLength());
1006
        strCmdline.ReleaseBuffer();
1007
 
1008
        strCmdline+=_TCHAR(' ');
1009
        strCmdline+=strFileName;
1010
        PROCESS_INFORMATION pi;
1011
        STARTUPINFO si;
1012
 
1013
        si.cb = sizeof(STARTUPINFO);
1014
        si.lpReserved = NULL;
1015
        si.lpReserved2 = NULL;
1016
        si.cbReserved2 = 0;
1017
        si.lpDesktop = NULL;
1018
        si.dwFlags = 0;
1019
        si.lpTitle=NULL;
1020
 
1021
        if(CreateProcess(
1022
            NULL, // app name
1023
            //strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
1024
            strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
1025
            NULL, // process security
1026
            NULL, // thread security
1027
            TRUE, // inherit handles
1028
            0,
1029
            NULL, // environment
1030
            NULL, // current dir
1031
            &si, // startup info
1032
            &pi)){
1033
            CloseHandle(pi.hProcess);
1034
            CloseHandle(pi.hThread);
1035
            rc=true;
1036
        } else {
1037
            CUtils::MessageBoxF(_T("Failed to invoke %s.\n"),strCmdline);
1038
        }
1039
        strCmdline.ReleaseBuffer();
1040
    } else {// Use association
1041
        TCHAR szExe[MAX_PATH];
1042
        HINSTANCE h=FindExecutable(strFileName,_T("."),szExe);
1043
        if(int(h)<=32){
1044
            CString str;
1045
            switch(int(h)){
1046
            case 0:  str=_T("The system is out of memory or resources.");break;
1047
            case 31: str=_T("There is no association for the specified file type.");break;
1048
            case ERROR_FILE_NOT_FOUND: str=_T("The specified file was not found.");break;
1049
            case ERROR_PATH_NOT_FOUND: str=_T("The specified path was not found.");break;
1050
            case ERROR_BAD_FORMAT:     str=_T("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).");break;
1051
            default: break;
1052
            }
1053
            CUtils::MessageBoxF(_T("Failed to open document %s.\r\n%s"),strFileName,str);
1054
        } else {
1055
 
1056
            SHELLEXECUTEINFO sei = {sizeof(sei), 0, AfxGetMainWnd()->GetSafeHwnd(), _T("open"),
1057
                strFileName, NULL, NULL, SW_SHOWNORMAL, AfxGetInstanceHandle( )};
1058
 
1059
            sei.hInstApp=0;
1060
            HINSTANCE hInst=ShellExecute(AfxGetMainWnd()->GetSafeHwnd(),_T("open"), strFileName, NULL, _T("."), 0)/*ShellExecuteEx(&sei)*/;
1061
            if(int(hInst)<=32/*sei.hInstApp==0*/)
1062
            {
1063
                CString str;
1064
                switch(int(hInst))
1065
                {
1066
                case 0 : str=_T("The operating system is out of memory or resources. ");break;
1067
                case ERROR_FILE_NOT_FOUND : str=_T("The specified file was not found. ");break;
1068
                case ERROR_PATH_NOT_FOUND : str=_T("The specified path was not found. ");break;
1069
                case ERROR_BAD_FORMAT : str=_T("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image). ");break;
1070
                case SE_ERR_ACCESSDENIED : str=_T("The operating system denied access to the specified file. ");break;
1071
                case SE_ERR_ASSOCINCOMPLETE : str=_T("The filename association is incomplete or invalid. ");break;
1072
                case SE_ERR_DDEBUSY : str=_T("The DDE transaction could not be completed because other DDE transactions were being processed. ");break;
1073
                case SE_ERR_DDEFAIL : str=_T("The DDE transaction failed. ");break;
1074
                case SE_ERR_DDETIMEOUT : str=_T("The DDE transaction could not be completed because the request timed out. ");break;
1075
                case SE_ERR_DLLNOTFOUND : str=_T("The specified dynamic-link library was not found. ");break;
1076
                    //case SE_ERR_FNF : str=_T("The specified file was not found. ");break;
1077
                case SE_ERR_NOASSOC : str=_T("There is no application associated with the given filename extension. ");break;
1078
                case SE_ERR_OOM : str=_T("There was not enough memory to complete the operation. ");break;
1079
                    //case SE_ERR_PNF : str=_T("The specified path was not found. ");break;
1080
                case SE_ERR_SHARE : str=_T("A sharing violation occurred. ");break;
1081
                default: str=_T("An unexpected error occurred");break;
1082
                }
1083
                CUtils::MessageBoxF(_T("Failed to open document %s using %s.\r\n%s"),strFileName,szExe,str);
1084
            } else {
1085
                rc=true;
1086
            }
1087
        }
1088
    }
1089
    return rc;
1090
#endif
1091
}
1092
 
1093
bool ecApp::PrepareEnvironment(bool bWithBuildTools, wxString* cmdLine)
1094
{
1095
#ifdef __WXMSW__
1096
    // Under Windows we can set variables.
1097
    ecConfigToolDoc *pDoc = GetConfigToolDoc();
1098
 
1099
    wxSetEnv(wxT("PATH"), m_strOriginalPath);
1100
 
1101
    const wxString strPrefix(pDoc->GetCurrentTargetPrefix());
1102
    ecFileName strBinDir;
1103
    bool rc = FALSE;
1104
 
1105
    rc=(! bWithBuildTools) || GetSettings().m_arstrBinDirs.Find(strPrefix, strBinDir);
1106
    if(!rc)
1107
    {
1108
        // Use fallback of previously-entered build tools directory, if available
1109
        if (!GetSettings().m_buildToolsDir.IsEmpty())
1110
        {
1111
            strBinDir = GetSettings().m_buildToolsDir ;
1112
            rc = TRUE;
1113
        }
1114
        else
1115
        {
1116
            wxCommandEvent event;
1117
            GetMainFrame()->OnBuildToolsPath(event);
1118
            rc = GetSettings().m_arstrBinDirs.Find(strPrefix, strBinDir);
1119
        }
1120
    }
1121
 
1122
    if (rc)
1123
    {
1124
        ecFileName strUserBinDir(GetSettings().m_userToolsDir);
1125
        if(strUserBinDir.IsEmpty())
1126
        {
1127
            if ( 1 == GetSettings().m_userToolPaths.GetCount() )
1128
            {
1129
                GetSettings().m_userToolsDir = GetSettings().m_userToolPaths[0];
1130
            } else
1131
            {
1132
                wxCommandEvent event;
1133
                GetMainFrame()->OnUserToolsPath(event);
1134
            }
1135
            strUserBinDir = GetSettings().m_userToolsDir;
1136
        }
1137
        if ( !strUserBinDir.IsEmpty() )
1138
        {
1139
            // calculate the directory of the host tools from this application's module name
1140
            const wxFileName strConfigtoolFile(this->argv[0]);
1141
            const ecFileName strHostToolsBinDir(strConfigtoolFile.GetPath(wxPATH_GET_VOLUME, wxPATH_DOS));
1142
 
1143
            // tools directories are in the order host-tools, user-tools, comp-tools, install/bin (if present), contrib-tools (if present) on the path
1144
            const ecFileName strContribBinDir(strUserBinDir, wxT("..\\contrib\\bin"));
1145
            ecFileName strUsrBinDir(strUserBinDir, wxT("..\\usr\\bin"));
1146
            const ecFileName strInstallBinDir(pDoc->GetInstallTree (), wxT("bin"));
1147
 
1148
            // In case strUserBinDir is e.g. c:\program files\red hat\cygwin-00r1\usertools\h-i686-pc-cygwin\bin
1149
            if (!strUsrBinDir.IsDir ())
1150
                strUsrBinDir = ecFileName(strUserBinDir + _T("..\\..\\..\\H-i686-pc-cygwin\\bin"));
1151
 
1152
            if (
1153
                (strUsrBinDir.IsDir ()     && ! ecUtils::AddToPath (strUsrBinDir)) ||
1154
                (strContribBinDir.IsDir () && ! ecUtils::AddToPath (strContribBinDir)) ||
1155
                (strInstallBinDir.IsDir () && ! ecUtils::AddToPath (strInstallBinDir)) ||
1156
                (bWithBuildTools && ! ecUtils::AddToPath (strBinDir)) ||
1157
                ! ecUtils::AddToPath (strUserBinDir) ||
1158
                ! ecUtils::AddToPath (strHostToolsBinDir))
1159
            {
1160
                wxString msg;
1161
                msg.Printf(wxT("Failed to set PATH environment variable"));
1162
                wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
1163
                rc = FALSE;
1164
            } else
1165
            {
1166
                if(!wxSetEnv(_T("MAKE_MODE"),_T("unix")))
1167
                {
1168
                    wxString msg;
1169
                    msg.Printf(wxT("Failed to set MAKE_MODE environment variable"));
1170
                    wxMessageBox(msg, wxGetApp().GetSettings().GetAppName(), wxICON_EXCLAMATION|wxOK);
1171
                    rc = FALSE;
1172
                } else
1173
                {
1174
                    // Remove from the environment
1175
                    wxUnsetEnv(wxT("GDBTK_LIBRARY"));
1176
                    wxUnsetEnv(wxT("GCC_EXEC_PREFIX"));
1177
 
1178
                    // Useful for ecosconfig
1179
                    wxSetEnv(wxT("ECOS_REPOSITORY"), pDoc->GetPackagesDir());
1180
                }
1181
            }
1182
        }
1183
    }
1184
    return rc;
1185
#else
1186
    wxASSERT ( cmdLine != NULL );
1187
 
1188
    (* cmdLine) = wxEmptyString;
1189
 
1190
    // Under Unix we need to build up a command line to set variables and invoke make
1191
    ecConfigToolDoc *pDoc = GetConfigToolDoc();
1192
 
1193
    const wxString strPrefix(pDoc->GetCurrentTargetPrefix());
1194
    ecFileName strBinDir;
1195
    bool rc = FALSE;
1196
 
1197
    rc=(! bWithBuildTools) || GetSettings().m_arstrBinDirs.Find(strPrefix, strBinDir);
1198
    if(!rc)
1199
    {
1200
        // Use fallback of previously-entered build tools directory, if available
1201
        if (!GetSettings().m_buildToolsDir.IsEmpty())
1202
        {
1203
            strBinDir = GetSettings().m_buildToolsDir ;
1204
            rc = TRUE;
1205
        }
1206
        else
1207
        {
1208
            wxCommandEvent event;
1209
            GetMainFrame()->OnBuildToolsPath(event);
1210
            rc = GetSettings().m_arstrBinDirs.Find(strPrefix, strBinDir);
1211
        }
1212
    }
1213
 
1214
    if (rc)
1215
    {
1216
        if (!strBinDir.IsEmpty())
1217
        {
1218
            (* cmdLine) += wxString(wxT("export PATH=")) + wxString(strBinDir) + wxT(":$PATH; ");
1219
 
1220
            // Also set the path
1221
            wxString oldPath(wxGetenv(wxT("PATH")));
1222
            wxString path(strBinDir);
1223
            if (!oldPath.IsEmpty())
1224
            {
1225
                path += wxT(":");
1226
                path += oldPath;
1227
            }
1228
            wxSetEnv(wxT("PATH"), path);
1229
        }
1230
        (* cmdLine) += wxString(wxT("unset GDBTK_LIBRARY; ")) ;
1231
        wxUnsetEnv(wxT("GDBTK_LIBRARY"));
1232
 
1233
        (* cmdLine) += wxString(wxT("unset GCC_EXEC_PREFIX; ")) ;
1234
        wxUnsetEnv(wxT("GCC_EXEC_PREFIX"));
1235
 
1236
        (* cmdLine) += wxString(wxT("export ECOS_REPOSITORY=")) + wxString(pDoc->GetPackagesDir()) + wxT("; ");
1237
        wxSetEnv(wxT("ECOS_REPOSITORY"), pDoc->GetPackagesDir());
1238
 
1239
#if 0
1240
        ecFileName strUserBinDir(GetSettings().m_userToolsDir);
1241
        if(strUserBinDir.IsEmpty())
1242
        {
1243
            if ( 1 == GetSettings().m_userToolPaths.GetCount() )
1244
            {
1245
                GetSettings().m_userToolsDir = GetSettings().m_userToolPaths[0];
1246
            } else
1247
            {
1248
                wxCommandEvent event;
1249
                GetMainFrame()->OnUserToolsPath(event);
1250
            }
1251
            strUserBinDir = GetSettings().m_userToolsDir;
1252
        }
1253
        if ( !strUserBinDir.IsEmpty() )
1254
        {
1255
            // calculate the directory of the host tools from this application's module name
1256
            ecFileName strHostToolsBinDir(this->argv[0]);
1257
            strHostToolsBinDir = strHostToolsBinDir.Head ();
1258
 
1259
            // tools directories are in the order host-tools, user-tools, comp-tools, install/bin (if present), contrib-tools (if present) on the path
1260
 
1261
            // TODO: is this right? Assuming that the user tools are already in the user's path.
1262
            // const ecFileName strContribBinDir(strUserBinDir, wxT("..\\contrib\\bin"));
1263
            // const ecFileName strUsrBinDir(strUserBinDir, wxT("..\\usr\\bin"));
1264
            const ecFileName strInstallBinDir(pDoc->GetInstallTree (), wxT("bin"));
1265
 
1266
            (* cmdLine) += wxString(wxT("export PATH=")) + wxString(strInstallBinDir) + wxT(":$PATH; ");
1267
            (* cmdLine) += wxString(wxT("unset GDBTK_LIBRARY; ")) ;
1268
            (* cmdLine) += wxString(wxT("unset GCC_EXEC_PREFIX; ")) ;
1269
            (* cmdLine) += wxString(wxT("export ECOS_REPOSITORY=")) + wxString(pDoc->GetPackagesDir()) + wxT("; ");
1270
        }
1271
#endif
1272
    }
1273
    return rc;
1274
#endif
1275
}
1276
 
1277
void ecApp::Build(const wxString &strWhat /*=wxT("")*/ )
1278
{
1279
    if (m_pipedProcess)
1280
        return;
1281
 
1282
    ecConfigToolDoc* pDoc = GetConfigToolDoc();
1283
    if (!pDoc)
1284
        return;
1285
 
1286
    if (!wxGetApp().GetMainFrame()->GetOutputWindow()->IsShown())
1287
    {
1288
        wxGetApp().GetMainFrame()->ToggleWindow(ecID_TOGGLE_OUTPUT);
1289
    }
1290
    if (!pDoc->GetDocumentSaved()) // if document has never been saved
1291
    {
1292
        if (!pDoc->SaveAs())
1293
            return; // user chose not to save the unsaved document so cannot build eCos
1294
    }
1295
 
1296
    if (pDoc->IsModified()) // if document has been modified since last save
1297
    {
1298
        if (wxOK == wxMessageBox("Building eCos will save changes to your current eCos configuration.",
1299
            "Build", wxOK|wxCANCEL|wxICON_EXCLAMATION))
1300
            pDoc->Save();
1301
        else
1302
            return; // user chose not to save changes so cannot build eCos
1303
    }
1304
 
1305
    // save an eCos configuration which is already saved but is without a corresponding build tree
1306
    if (!wxDirExists(pDoc->GetBuildTree()))
1307
    {
1308
        pDoc->Save();
1309
    }
1310
 
1311
    if ( pDoc->GetDocumentSaved() )
1312
    {
1313
        //wxString strCmd (wxT("c:\\bin\\testmake.bat"));
1314
        wxString strCmd (wxT("make"));
1315
        if(!strWhat.IsEmpty())
1316
        {
1317
            strCmd += wxT(' ');
1318
            strCmd += strWhat;
1319
        }
1320
 
1321
        if(!GetSettings().m_strMakeOptions.IsEmpty())
1322
        {
1323
            strCmd += wxT(' ');
1324
            strCmd += GetSettings().m_strMakeOptions;
1325
        }
1326
        strCmd += wxT(" --directory ");
1327
 
1328
        // Quoting the name may not mix with the 'sh' command on Unix, so only do it
1329
        // under Windows where it's more likely there will be spaces needing quoting.
1330
#ifdef __WXMSW__
1331
        wxString buildDir(pDoc->GetBuildTree());
1332
 
1333
#if ecUSE_ECOS_X_NOTATION
1334
        std::string cPath = cygpath(std::string(pDoc->GetBuildTree()));
1335
        buildDir = cPath.c_str();
1336
#endif
1337
        strCmd += wxString(wxT("\"")) + buildDir + wxString(wxT("\""));
1338
#else
1339
        strCmd += wxString(pDoc->GetBuildTree()) ;
1340
#endif
1341
 
1342
        wxString variableSettings;
1343
 
1344
        if (PrepareEnvironment(TRUE, & variableSettings))
1345
        {
1346
#ifdef __WXMSW__
1347
            // strCmd is all we need
1348
#else
1349
            // strCmd has to invoke a shell with variables and make invocation
1350
            strCmd = wxString(wxT("sh -c \"")) + variableSettings + strCmd + wxString(wxT("\""));
1351
#endif
1352
            // Output the command so we know what we're doing
1353
            Log(strCmd);
1354
            Log(wxT("\n"));
1355
 
1356
            // No: pass --directory
1357
            // wxSetWorkingDirectory(pDoc->GetBuildTree());
1358
 
1359
            m_pipedProcess = new ecPipedProcess;
1360
            long pid = wxExecute(strCmd, FALSE, m_pipedProcess);
1361
            if ( pid )
1362
            {
1363
                m_pipedProcess->SetPid(pid);
1364
                // wxLogStatus(_T("Process %ld (%s) launched."), pid, cmd.c_str());
1365
            }
1366
            else
1367
            {
1368
                wxLogError(_T("Execution of '%s' failed."), strCmd.c_str());
1369
 
1370
                delete m_pipedProcess;
1371
                m_pipedProcess  = NULL;
1372
            }
1373
        }
1374
 
1375
#if 0        
1376
        if(PrepareEnvironment())
1377
        {
1378
            m_strBuildTarget=strWhat;
1379
            SetThermometerMax(250); // This is just a guess.  The thread we are about to spawn will work out the correct answer
1380
            m_nLogicalLines=0;
1381
            UpdateThermometer(0);
1382
            CloseHandle(CreateThread(NULL, 0, ThreadFunc, this, 0 ,&m_dwThreadId));
1383
            CString strMsg;
1384
            strMsg.Format(_T("Building %s"),strWhat);
1385
            SetIdleMessage(strMsg);
1386
 
1387
            SetTimer(42,1000,0); // This timer checks for process completion
1388
            SetCurrentDirectory(pDoc->BuildTree());
1389
            m_sp.Run(SubprocessOutputFunc, this, strCmd, false);
1390
            SetIdleMessage();
1391
        }
1392
#endif
1393
    }
1394
#if 0
1395
 
1396
    if(pDoc->IsModified()||pDoc->BuildTree().IsEmpty()){
1397
        SendMessage (WM_COMMAND, ID_FILE_SAVE);
1398
    }
1399
 
1400
    if(!(pDoc->IsModified()||pDoc->BuildTree().IsEmpty())){ // verify the save worked
1401
        CString strCmd (_T("make"));
1402
        if(!strWhat.IsEmpty()){
1403
            strCmd+=_TCHAR(' ');
1404
            strCmd+=strWhat;
1405
        }
1406
        if(!GetApp()->m_strMakeOptions.IsEmpty()){
1407
            strCmd+=_TCHAR(' ');
1408
            strCmd+=GetApp()->m_strMakeOptions;
1409
        }
1410
 
1411
        if(PrepareEnvironment()){
1412
            m_strBuildTarget=strWhat;
1413
            SetThermometerMax(250); // This is just a guess.  The thread we are about to spawn will work out the correct answer
1414
            m_nLogicalLines=0;
1415
            UpdateThermometer(0);
1416
            CloseHandle(CreateThread(NULL, 0, ThreadFunc, this, 0 ,&m_dwThreadId));
1417
            CString strMsg;
1418
            strMsg.Format(_T("Building %s"),strWhat);
1419
            SetIdleMessage(strMsg);
1420
 
1421
            SetTimer(42,1000,0); // This timer checks for process completion
1422
            SetCurrentDirectory(pDoc->BuildTree());
1423
            m_sp.Run(SubprocessOutputFunc, this, strCmd, false);
1424
            SetIdleMessage();
1425
        }
1426
    }
1427
#endif
1428
}
1429
 
1430
void ecApp::OnProcessTerminated(wxProcess* process)
1431
{
1432
    m_pipedProcess = NULL;
1433
}
1434
 
1435
// ----------------------------------------------------------------------------
1436
// ecPipedProcess
1437
// ----------------------------------------------------------------------------
1438
 
1439
bool ecPipedProcess::HasInput()
1440
{
1441
    bool hasInput = FALSE;
1442
 
1443
    wxInputStream& is = *GetInputStream();
1444
    if ( IsInputAvailable() )
1445
    {
1446
        wxTextInputStream tis(is);
1447
 
1448
        // this assumes that the output is always line buffered
1449
        wxString msg;
1450
        msg << tis.ReadLine();
1451
 
1452
        wxGetApp().Log(msg);
1453
 
1454
        hasInput = TRUE;
1455
    }
1456
 
1457
    wxInputStream& es = *GetErrorStream();
1458
    if ( IsErrorAvailable() )
1459
    {
1460
        wxTextInputStream tis(es);
1461
 
1462
        // this assumes that the output is always line buffered
1463
        wxString msg;
1464
        msg << tis.ReadLine();
1465
 
1466
        wxGetApp().Log(msg);
1467
 
1468
        hasInput = TRUE;
1469
    }
1470
 
1471
    return hasInput;
1472
}
1473
 
1474
void ecPipedProcess::OnTerminate(int pid, int status)
1475
{
1476
    // show the rest of the output
1477
    while ( HasInput() )
1478
        ;
1479
 
1480
    wxGetApp().OnProcessTerminated(this);
1481
 
1482
    //wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."),
1483
    //            pid, m_cmd.c_str(), status);
1484
 
1485
    // we're not needed any more
1486
    delete this;
1487
}
1488
 
1489
void ecPingTimer::Notify()
1490
{
1491
    static bool s_inNotify = FALSE;
1492
 
1493
    if (s_inNotify)
1494
        return;
1495
 
1496
    s_inNotify = TRUE;
1497
 
1498
    // On Windows, simply having the timer going will ping the message queue
1499
    // and cause idle processing to happen.
1500
    // On Unix, this doesn't happen so we have to do the processing explicitly.
1501
#ifdef __WXMSW__
1502
    // Nothing to do
1503
#else
1504
    // Get some input
1505
    if ( wxGetApp().m_pipedProcess )
1506
        while (wxGetApp().m_pipedProcess->HasInput())
1507
        {
1508
            // Loop while there is still input
1509
        }
1510
#endif
1511
 
1512
    s_inNotify = FALSE;
1513
}
1514
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.