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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-3.0/] [host/] [tools/] [configtool/] [common/] [win32/] [CTCommonDoc.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 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
#include "stdafx.h"
23
 
24
#include "ConfigToolDoc.h"
25
 
26
#ifdef PLUGIN
27
  #include "CTMain.h"
28
  #include "Project.h"
29
  #include "ProjectManager.h"
30
#else
31
  #include "MainFrm.h"
32
#endif
33
 
34
#include "CTUtils.h"
35
#include "CdlPackagesDialog.h"
36
#include "ConfigItem.h"
37
#include "ConfigTool.h"
38
#include "ControlView.h"
39
#include "FailingRulesDialog.h"
40
#include "FolderDialog.h"
41
#include "IdleMessage.h"
42
#include "MLTView.h"
43
#include "NotePage.h"
44
#include "RegionGeneralPage.h"
45
#include "RegKeyEx.h"
46
#include "RulesView.h"
47
#include "SectionGeneralPage.h"
48
#include "SectionRelocationPage.h"
49
 
50
#include <htmlhelp.h>
51
#include <shlobj.h>
52
 
53
#define INCLUDEFILE <string>
54
#include "IncludeSTL.h"
55
#define INCLUDEFILE "build.hxx"
56
#include "IncludeSTL.h"
57
 
58
#ifdef _DEBUG
59
  #define new DEBUG_NEW
60
  #undef THIS_FILE
61
  static char THIS_FILE[] = __FILE__;
62
#endif
63
 
64
const CFileName &CConfigToolDoc::DefaultExternalBrowser()
65
{
66
  static bool bFirstTime=true;
67
  if(bFirstTime){
68
    const CFileName strFile(CFileName::GetTempPath()+_T("index.html"));
69
    CFile f;
70
    if(f.Open(strFile,CFile::modeCreate|CFile::modeWrite)){
71
      f.Close();
72
      bool rc=((int)FindExecutable(strFile,_T("."),m_strDefaultExternalBrowser.GetBuffer(MAX_PATH))>32);
73
      m_strDefaultExternalBrowser.ReleaseBuffer();
74
      if(!rc){
75
        m_strDefaultExternalBrowser=_T("");
76
      }
77
      ::DeleteFile(strFile);
78
    }
79
    bFirstTime=false;
80
  }
81
  return m_strDefaultExternalBrowser;
82
}
83
 
84
CFileName CConfigToolDoc::m_strDefaultExternalBrowser;
85
 
86
void CConfigToolDoc::CheckRadios()
87
{
88
  for(int nItem=0;nItem<ItemCount();nItem++){
89
    CConfigItem *pItem=Item(nItem);
90
    if(pItem->HasRadio () && pItem==pItem->FirstRadio()){
91
      CString strMsg;
92
      CConfigItem *pFirstSet=NULL;
93
      for(CConfigItem *pSibItem=pItem;pSibItem;pSibItem=pSibItem->NextRadio()){
94
        if(pSibItem->IsEnabled ()){
95
          if(pFirstSet){
96
            strMsg+=_T(" ");
97
            strMsg+=pSibItem->Macro ();
98
          } else {
99
            pFirstSet=pSibItem;
100
          }
101
        }
102
      }
103
      if(!strMsg.IsEmpty()){
104
        CConfigTool::Log(_T("%s, multiple radio buttons are set: %s%s"),
105
          pItem->Macro(),pFirstSet->Macro(),strMsg);
106
      } else if(!pFirstSet){
107
        CConfigTool::Log(_T("%s, no radio buttons are set"),pItem->Macro());
108
      }
109
    }
110
  }
111
}
112
 
113
// Find the ConfigItem referencing the given CdlValuable
114
CConfigItem * CConfigToolDoc::Find (CdlValuable v)
115
{
116
  for(int nItem=0;nItem<ItemCount();nItem++){
117
    CConfigItem *pItem=Item(nItem);
118
    if(v==pItem->GetCdlValuable()){
119
      return pItem;
120
    }
121
  }
122
  return NULL;
123
}
124
 
125
CConfigItem * CConfigToolDoc::Find(const CString & strWhat,WhereType where)
126
{
127
  for(int nItem=0;nItem<ItemCount();nItem++){
128
    CConfigItem *pItem=Item(nItem);
129
    if(0==pItem->StringValue(where).Compare(strWhat)){
130
      return pItem;
131
    }
132
  }
133
  return NULL;
134
}
135
 
136
void CConfigToolDoc::OnMLTNewRegion()
137
{
138
  // create the property sheet
139
 
140
  CPropertySheet prsRegionSheet (IDS_NEW_REGION_SHEET_TITLE, CConfigTool::GetMLTView());
141
 
142
  // add the property pages
143
 
144
  CRegionGeneralPage prpGeneral;
145
  CNotePage prpNote;
146
 
147
  prsRegionSheet.AddPage (&prpGeneral);
148
  prsRegionSheet.AddPage (&prpNote);
149
 
150
  // setup initial values
151
 
152
  prpGeneral.m_strRegionName = _T("");
153
  prpGeneral.m_dwRegionStartAddress = 0;
154
  prpGeneral.m_dwRegionSize = 0;
155
 
156
  // show property sheet
157
 
158
  if (prsRegionSheet.DoModal () == IDOK)
159
  {
160
    if (int nErrorCode = MemoryMap.create_memory_region (CUtils::UnicodeToStdStr(prpGeneral.m_strRegionName), prpGeneral.m_dwRegionStartAddress, prpGeneral.m_dwRegionSize, (prpGeneral.m_bRegionReadOnly ? read_only : read_write), CUtils::UnicodeToStdStr(prpNote.m_strNote)))
161
      ErrorBox (IDS_ERR_MEMMAP_REGION_CREATE, IDS_ERR_MEMMAP_BASE + nErrorCode);
162
    else // no errors
163
    {
164
      SetModifiedFlag ();
165
      UpdateAllViews (NULL, MemLayoutChanged);
166
    }
167
  }
168
}
169
 
170
void CConfigToolDoc::ErrorBox (UINT uIDSIntro, UINT uIDSError)
171
{
172
  CString strIntro, strError;
173
  strIntro.LoadString (uIDSIntro);
174
  strError.LoadString (uIDSError);
175
  AfxMessageBox (strIntro + _T("\n\n") + strError);
176
}
177
 
178
void CConfigToolDoc::OnMLTNewSection()
179
{
180
  // create the property sheet
181
 
182
  CPropertySheet prsSectionSheet (IDS_NEW_SECTION_SHEET_TITLE, CConfigTool::GetMLTView());
183
 
184
  // add the property pages
185
 
186
  CSectionGeneralPage prpGeneral;
187
  CSectionRelocationPage prpRelocation;
188
  CNotePage prpNote;
189
 
190
  prsSectionSheet.AddPage (&prpGeneral);
191
  prsSectionSheet.AddPage (&prpRelocation);
192
  prsSectionSheet.AddPage (&prpNote);
193
 
194
  // initialise for a new section
195
 
196
  prpGeneral.m_bNameLinkerDefined = TRUE;
197
  prpGeneral.m_strNameLinker = _T("");
198
  prpRelocation.m_bRelocates = FALSE;
199
  prpRelocation.m_bNewSection = TRUE;
200
 
201
  // show property sheet
202
 
203
  if (prsSectionSheet.DoModal () == IDOK)
204
  {
205
    mem_anchor initial_anchor, final_anchor;
206
    mem_address initial_address;
207
    CString strInitialRelativeName = _T("");
208
 
209
    if (prpGeneral.m_bFinalAbsolute) // final location is an absolute location
210
      final_anchor = absolute;
211
    else // final location is a relative location
212
      final_anchor = relative;
213
 
214
    if (prpRelocation.m_bRelocates) // if the section relocates
215
    {
216
      if (prpRelocation.m_bInitialAbsolute) // initial location is an absolute location
217
      {
218
        initial_anchor = absolute;
219
      }
220
      else // initial location is a relative location
221
      {
222
        strInitialRelativeName = prpRelocation.m_strInitialRelativeName;
223
        initial_anchor = relative;
224
      }
225
      initial_address = prpRelocation.m_dwInitialAddress;
226
    }
227
    else
228
    {
229
      strInitialRelativeName = prpGeneral.m_strFinalRelativeName;
230
      initial_anchor = final_anchor;
231
      initial_address = prpGeneral.m_dwFinalAddress;
232
    }
233
 
234
 
235
    if (int nErrorCode = MemoryMap.create_memory_section (CUtils::UnicodeToStdStr(prpGeneral.m_bNameLinkerDefined ? prpGeneral.m_strNameLinker : prpGeneral.m_strNameUser), prpGeneral.m_dwSectionSize, prpGeneral.m_dwAlignment, initial_anchor, CUtils::UnicodeToStdStr(strInitialRelativeName), initial_address, final_anchor, CUtils::UnicodeToStdStr(prpGeneral.m_strFinalRelativeName), prpGeneral.m_dwFinalAddress, prpRelocation.m_bRelocates, false, prpGeneral.m_bNameLinkerDefined, CUtils::UnicodeToStdStr(prpNote.m_strNote)))
236
      ErrorBox (IDS_ERR_MEMMAP_SECTION_CREATE, IDS_ERR_MEMMAP_BASE + nErrorCode);
237
    else // no errors
238
    {
239
      SetModifiedFlag ();
240
      UpdateAllViews (NULL, MemLayoutChanged);
241
    }
242
  }
243
}
244
 
245
void CConfigToolDoc::OnMLTDelete()
246
{
247
  if (strSelectedSection != _T("")) // a section is selected
248
  {
249
    if (MemoryMap.delete_memory_section (CUtils::UnicodeToStdStr(strSelectedSection)))
250
    {
251
      strSelectedSection = _T("");
252
      SetModifiedFlag ();
253
      UpdateAllViews (NULL, MemLayoutChanged);
254
    }
255
    else
256
      AfxMessageBox (_T("Could not delete memory section.\n\nMake sure there are no other sections defined relative to this one."));
257
  }
258
  else if (strSelectedRegion != _T("")) // a region is selected
259
  {
260
    if (MemoryMap.delete_memory_region (CUtils::UnicodeToStdStr(strSelectedRegion)))
261
    {
262
      strSelectedRegion = _T("");
263
      SetModifiedFlag ();
264
      UpdateAllViews (NULL, MemLayoutChanged);
265
    }
266
    else
267
      AfxMessageBox (_T("Could not delete memory region.\n\nMake sure it is not in use.")); // FIXME
268
  }
269
}
270
 
271
void CConfigToolDoc::ShowRegionProperties()
272
{
273
  // create the property sheet
274
 
275
  CString strTitle;
276
  strTitle.LoadString (IDS_REGION_PROPERTIES_SHEET_TITLE);
277
  CPropertySheet prsRegionSheet (strSelectedRegion + _T(" - ") + strTitle, CConfigTool::GetMLTView());
278
 
279
  // add the property pages
280
 
281
  CRegionGeneralPage prpGeneral;
282
  CNotePage prpNote;
283
 
284
  prsRegionSheet.AddPage (&prpGeneral);
285
  prsRegionSheet.AddPage (&prpNote);
286
 
287
  // set up property sheet values
288
 
289
  mem_type type;
290
  std::string note;
291
  MemoryMap.get_memory_region (CUtils::UnicodeToStdStr(strSelectedRegion), &prpGeneral.m_dwRegionStartAddress, &prpGeneral.m_dwRegionSize, &type, &note);
292
  prpGeneral.m_strRegionName = strSelectedRegion;
293
  prpGeneral.m_bRegionReadOnly = (type == read_only);
294
  prpNote.m_strNote = note.c_str ();
295
 
296
  // show property sheet
297
 
298
  if (prsRegionSheet.DoModal () == IDOK)
299
  {
300
    if (int nErrorCode = MemoryMap.edit_memory_region (CUtils::UnicodeToStdStr(strSelectedRegion), CUtils::UnicodeToStdStr(prpGeneral.m_strRegionName), prpGeneral.m_dwRegionStartAddress, prpGeneral.m_dwRegionSize, (prpGeneral.m_bRegionReadOnly ? read_only : read_write), CUtils::UnicodeToStdStr(prpNote.m_strNote)))
301
      ErrorBox (IDS_ERR_MEMMAP_REGION_MODIFY, IDS_ERR_MEMMAP_BASE + nErrorCode);
302
    else // no errors
303
    {
304
      SetModifiedFlag ();
305
      UpdateAllViews (NULL, MemLayoutChanged);
306
    }
307
  }
308
}
309
 
310
void CConfigToolDoc::ShowSectionProperties()
311
{
312
  // create the property sheet
313
 
314
  CString strTitle;
315
  strTitle.LoadString (IDS_SECTION_PROPERTIES_SHEET_TITLE);
316
  CPropertySheet prsSectionSheet (strSelectedSection + _T(" - ") + strTitle, CConfigTool::GetMLTView());
317
 
318
  // add the property pages
319
 
320
  CSectionGeneralPage prpGeneral;
321
  CSectionRelocationPage prpRelocation;
322
  CNotePage prpNote;
323
 
324
  prsSectionSheet.AddPage (&prpGeneral);
325
  prsSectionSheet.AddPage (&prpRelocation);
326
  prsSectionSheet.AddPage (&prpNote);
327
 
328
  // setup initial values
329
 
330
  std::list <mem_section>::iterator section = MemoryMap.find_memory_section (CUtils::UnicodeToStdStr(strSelectedSection));
331
  prpGeneral.m_bNameLinkerDefined = (section->linker_defined);
332
  if (prpGeneral.m_bNameLinkerDefined)
333
    prpGeneral.m_strNameLinker = section->name.c_str ();
334
  else
335
  {
336
    prpGeneral.m_strNameUser = section->name.c_str ();
337
    prpGeneral.m_dwSectionSize = section->size;
338
  }
339
 
340
  prpGeneral.m_bFinalAbsolute = (section->final_location->anchor == absolute);
341
  if (prpGeneral.m_bFinalAbsolute)
342
    prpGeneral.m_dwFinalAddress = section->final_location->address;
343
  else
344
  {
345
    prpGeneral.m_strFinalRelativeName = MemoryMap.find_preceding_section (section, false)->name.c_str ();
346
    prpGeneral.m_dwAlignment = section->alignment;
347
  }
348
 
349
  prpRelocation.m_bRelocates = section->relocates;
350
  if (prpRelocation.m_bRelocates)
351
  {
352
    prpRelocation.m_bInitialAbsolute = (section->initial_location->anchor == absolute);
353
    if (prpRelocation.m_bInitialAbsolute)
354
      prpRelocation.m_dwInitialAddress = section->initial_location->address;
355
    else
356
      prpRelocation.m_strInitialRelativeName = MemoryMap.find_preceding_section (section, true)->name.c_str ();
357
  }
358
 
359
  prpNote.m_strNote = section->note.c_str ();
360
 
361
  // show property sheet
362
 
363
  if (prsSectionSheet.DoModal () == IDOK)
364
  {
365
    mem_anchor initial_anchor, final_anchor;
366
    mem_address initial_address;
367
    CString strInitialRelativeName = _T("");
368
 
369
    if (prpGeneral.m_bFinalAbsolute) // final location is an absolute location
370
      final_anchor = absolute;
371
    else // final location is a relative location
372
      final_anchor = relative;
373
 
374
    if (prpRelocation.m_bRelocates) // if the section relocates
375
    {
376
      if (prpRelocation.m_bInitialAbsolute) // initial location is an absolute location
377
      {
378
        initial_anchor = absolute;
379
      }
380
      else // initial location is a relative location
381
      {
382
        strInitialRelativeName = prpRelocation.m_strInitialRelativeName;
383
        initial_anchor = relative;
384
      }
385
      initial_address = prpRelocation.m_dwInitialAddress;
386
    }
387
    else
388
    {
389
      strInitialRelativeName = prpGeneral.m_strFinalRelativeName;
390
      initial_anchor = final_anchor;
391
      initial_address = prpGeneral.m_dwFinalAddress;
392
    }
393
 
394
 
395
    if (int nErrorCode = MemoryMap.edit_memory_section (CUtils::UnicodeToStdStr(strSelectedSection), CUtils::UnicodeToStdStr(prpGeneral.m_bNameLinkerDefined ? prpGeneral.m_strNameLinker : prpGeneral.m_strNameUser), prpGeneral.m_dwSectionSize, prpGeneral.m_dwAlignment, initial_anchor, CUtils::UnicodeToStdStr(strInitialRelativeName), initial_address, final_anchor, CUtils::UnicodeToStdStr(prpGeneral.m_strFinalRelativeName), prpGeneral.m_dwFinalAddress, prpRelocation.m_bRelocates, false, prpGeneral.m_bNameLinkerDefined, CUtils::UnicodeToStdStr(prpNote.m_strNote)))
396
      ErrorBox (IDS_ERR_MEMMAP_SECTION_MODIFY, IDS_ERR_MEMMAP_BASE + nErrorCode);
397
    else // no errors
398
    {
399
      SetModifiedFlag ();
400
      UpdateAllViews (NULL, MemLayoutChanged);
401
    }
402
  }
403
}
404
 
405
void CConfigToolDoc::OnMLTProperties()
406
{
407
  if (strSelectedRegion != _T(""))
408
    ShowRegionProperties ();
409
  else if (strSelectedSection != _T(""))
410
    ShowSectionProperties ();
411
}
412
 
413
// Choose a default Hal.  Do this using clues the installer may have helpfully left behind (PR 18050)
414
// or else if there is only one possible choice, by choosing that one :-).
415
/*
416
void CConfigToolDoc::ChooseDefaultHal()
417
{
418
bool bFound=false;
419
// Has the installer told us?
420
LPCTSTR pszRegPath=_T("SOFTWARE\\Red Hat\\eCos\\1.2.8");
421
HKEY hKey;
422
if(ERROR_SUCCESS==RegOpenKeyEx (HKEY_LOCAL_MACHINE, pszRegPath, 0L, KEY_READ, &hKey)){
423
DWORD dwSizePath=MAX_PATH;
424
CString str;
425
PTCHAR psz=str.GetBuffer(dwSizePath);
426
if(ERROR_SUCCESS==RegQueryValueEx(hKey, _T("Default Architecture"), NULL, NULL, (LPBYTE)psz, &dwSizePath)){
427
str.MakeLower();
428
for(int nItem=0;nItem<ItemCount();nItem++){
429
CConfigItem *pItem=Item(nItem);
430
if(pItem->m_pTarget){
431
CString strTarget(pItem->m_pTarget->Name());
432
strTarget.MakeLower();
433
if(-1!=str.Find(strTarget)){
434
bFound=true;
435
dwSizePath=MAX_PATH;
436
if(ERROR_SUCCESS==::RegQueryValueEx(hKey, _T("Default Build Tools Path"), NULL, NULL, (LPBYTE)psz, &dwSizePath)){
437
pItem->m_pTarget->SetBinDir(psz);
438
for(CConfigItem *pSib=pItem->FirstRadio();pSib;pSib=pSib->NextRadio()){
439
pSib->SetValue((ItemIntegerType) (pSib==pItem));
440
}
441
//                            pItem->EnableAncestors();
442
}
443
break;
444
}
445
}
446
}
447
}
448
RegCloseKey(hKey);
449
}
450
 
451
  if(!bFound){
452
  // No - choose the Hal according to toolchain
453
  for(int nItem=0;nItem<ItemCount();nItem++){
454
  CConfigItem *pItem=Item(nItem);
455
  if(pItem->m_pTarget){
456
  CString strTarget(pItem->m_pTarget->Name());
457
  strTarget.MakeLower();
458
  for(int j=0;j<m_arstrToolChainPaths.GetSize();j++){
459
  CString strTools(m_arstrToolChainPaths[j]);
460
  strTools.MakeLower();
461
  if(-1!=strTools.Find(strTarget)){
462
  for(CConfigItem *pSib=pItem->FirstRadio();pSib;pSib=pSib->NextRadio()){
463
  pSib->SetValue((ItemIntegerType) (pSib==pItem));
464
  }
465
  return;
466
  }
467
  }
468
  }
469
  }
470
  }
471
  }
472
*/
473
 
474
bool CConfigToolDoc::SetValue (CConfigItem &ti, double dValue, CdlTransaction transaction/*=NULL*/)
475
{
476
  ASSERT (ti.Type () == CConfigItem::Double);
477
 
478
  // test if the new double value is in range
479
  const CdlValuable valuable = ti.GetCdlValuable();
480
  CdlListValue list_value;
481
  CdlEvalContext context (NULL, ti.GetCdlItem (), ti.GetCdlItem ()->get_property (CdlPropertyId_LegalValues));
482
  valuable->get_legal_values ()->eval (context, list_value);
483
  if (! list_value.is_member (dValue))
484
  {
485
    if (dValue==valuable->get_double_value(CdlValueSource_Current) || IDNO == CUtils::MessageBoxFT (MB_YESNO, _T("%s is not a legal value for %s.\n\nDo you want to use this value anyway?"),
486
      CUtils::DoubleToStr (dValue), ti.Macro ()))
487
      return false;
488
  }
489
 
490
  if (! ti.SetValue (dValue,transaction))
491
    return false;
492
 
493
  SetModifiedFlag ();
494
  return true;
495
}
496
bool CConfigToolDoc::SetValue(CConfigItem &ti,const CString &strValue, CdlTransaction transaction/*=NULL*/)
497
{
498
  // warn the user if a modified memory layout is about to be discarded
499
  if (MemoryMap.map_modified () && (ti.Macro () == _T("CYG_HAL_STARTUP")) &&
500
    (IDCANCEL == CUtils::MessageBoxFT (MB_OKCANCEL, _T("Changes to the current memory layout will be lost."))))
501
    return false;
502
 
503
  bool rc=false;
504
  switch(ti.Type()){
505
                case CConfigItem::None:
506
      break;
507
    case CConfigItem::Enum:
508
    case CConfigItem::String:
509
      rc=ti.SetValue(strValue,transaction);
510
      break;
511
    case CConfigItem::Integer:
512
      {
513
        ItemIntegerType n;
514
        rc=CUtils::StrToItemIntegerType(strValue,n) && SetValue(ti,n,transaction);
515
      }
516
      break;
517
    case CConfigItem::Double:
518
      {
519
        double dValue;
520
        rc = CUtils::StrToDouble (strValue, dValue) && SetValue (ti, dValue,transaction);
521
      }
522
      break;
523
    default:
524
      ASSERT(FALSE);
525
      break;
526
 
527
  }
528
  if(rc){
529
    SetModifiedFlag();
530
    UpdateAllViews (NULL, CConfigToolDoc::ValueChanged, (CObject *)&ti);
531
  }
532
  return rc;
533
}
534
 
535
// Look in registry to match prefixes CYGPKG_HAL_ and CYGHWR_HAL_:
536
//
537
bool CConfigToolDoc::GetRunPlatform(CString &strTarget)
538
{
539
  CRegKeyEx k1(HKEY_CURRENT_USER,_T("Software\\Red Hat\\eCos\\Platforms"), KEY_READ);
540
  CString strKey;
541
  for(int i=0;k1.QueryKey(i,strKey);i++){
542
    CRegKeyEx k2((HKEY)k1,strKey,KEY_READ);
543
    // Subkeys' names are the target image names [one of which we aim to return]
544
    // Subkeys's values of interest are:
545
    //      Prefix  String
546
    //      Sim     DWORD  [optional]
547
    //      Macro   String 
548
    DWORD dwSim=0;
549
    CString strPrefix,strMacro;
550
    k2.QueryValue(_T("Sim"),dwSim);
551
    k2.QueryValue(_T("Prefix"),strPrefix);
552
    k2.QueryValue(_T("Macro"),strMacro);
553
 
554
    CConfigItem *pItem=Find(_T("CYGPKG_HAL_")+strMacro);
555
    if(pItem && pItem->IsEnabled()){
556
      // We have found what we are looking for - probably
557
      pItem=Find(_T("CYGHWR_HAL_")+strMacro+_T("_STARTUP"));
558
      if(pItem){
559
        // Two platforms apply - choose this one only if the ram startup attribute fits
560
        if( (dwSim==0) == (0==pItem->StringValue().CompareNoCase(_T("ram"))) ) {
561
          strTarget=strKey;
562
        }
563
      } else {
564
        // Only one platform applies
565
        strTarget=strKey;
566
      }
567
 
568
    }
569
  }
570
  return !strTarget.IsEmpty();
571
}
572
 
573
bool CConfigToolDoc::SetEnabled(CConfigItem &ti, bool bEnabled, CdlTransaction transaction/*=NULL*/)
574
{
575
  const bool bStatus = ti.SetEnabled (bEnabled,transaction);
576
 
577
  if (bStatus) {
578
    SetModifiedFlag();
579
    UpdateAllViews (NULL, CConfigToolDoc::ValueChanged, (CObject *) &ti);
580
  }
581
  return bStatus;
582
}
583
 
584
void CConfigToolDoc::AddContents (const CdlContainer container, CConfigItem *pParent)
585
{
586
 
587
  // determine the container contents
588
 
589
  const std::vector<CdlNode>& contents = container->get_contents ();
590
  std::vector<CdlNode>::const_iterator node_i;
591
  for (node_i = contents.begin (); node_i != contents.end (); node_i++)
592
  {
593
    const CdlNode node = * node_i;
594
    const CdlPackage pkg = dynamic_cast<CdlPackage> (node);
595
    const CdlComponent comp = dynamic_cast<CdlComponent> (node);
596
    const CdlOption opt = dynamic_cast<CdlOption> (node);
597
    const CdlContainer contnr = dynamic_cast<CdlContainer> (node);
598
 
599
    // if the node in the container is a package, component or option
600
    // then it is visible and should be added to the tree
601
    if  (0 != pkg) // the node is a package
602
    {
603
      CConfigItem * pItem = AddItem (pkg, pParent); // add the package
604
      AddContents (pkg, pItem); // add the package contents
605
    }
606
    else if (0 != comp) // the node is a component
607
    {
608
      CConfigItem * pItem = AddItem (comp, pParent); // add the component
609
      AddContents (comp, pItem); // add the component contents
610
    }
611
    else if (0 != opt) // the node is an option
612
      AddItem (opt, pParent); // add the option
613
 
614
    else if (0 != contnr) // if the node is a container
615
      AddContents (contnr, pParent); // add the container contents
616
 
617
    // ignore nodes of any other class
618
  }
619
}
620
 
621
// Three hack functions.
622
 
623
const CString CConfigToolDoc::CurrentPlatform()
624
{
625
/*
626
for(int nItem=0;nItem<ItemCount();nItem++){
627
CConfigItem *pItem=Item(nItem);
628
if(pItem->IsEnabled() && !pItem->Platform().IsEmpty()){
629
return pItem->Platform();
630
}
631
}
632
  */
633
  return _T("");
634
}
635
 
636
// a trivial CDL parse error handler
637
void CConfigToolDoc::CdlParseErrorHandler (std::string message)
638
{
639
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
640
  pDoc->m_strCdlErrorMessage = message.c_str ();
641
  TRACE (_T("CdlParseError: %s\n"), pDoc->m_strCdlErrorMessage);
642
  CConfigTool::Log (CUtils::StripExtraWhitespace (pDoc->m_strCdlErrorMessage)); // display the message in the output window
643
};
644
 
645
// a trivial CDL parse warning handler
646
void CConfigToolDoc::CdlParseWarningHandler (std::string message)
647
{
648
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
649
  pDoc->m_strCdlErrorMessage = message.c_str ();
650
  TRACE (_T("CdlParseWarning: %s\n"), pDoc->m_strCdlErrorMessage);
651
  CConfigTool::Log (CUtils::StripExtraWhitespace (pDoc->m_strCdlErrorMessage)); // display the message in the output window
652
};
653
 
654
// a trivial CDL load error handler
655
void CConfigToolDoc::CdlLoadErrorHandler (std::string message)
656
{
657
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
658
  pDoc->m_strCdlErrorMessage = message.c_str ();
659
  TRACE (_T("CdlLoadError: %s\n"), pDoc->m_strCdlErrorMessage);
660
  CConfigTool::Log (CUtils::StripExtraWhitespace (pDoc->m_strCdlErrorMessage)); // display the message in the output window
661
};
662
 
663
// a trivial CDL load warning handler
664
void CConfigToolDoc::CdlLoadWarningHandler (std::string message)
665
{
666
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
667
  pDoc->m_strCdlErrorMessage = message.c_str ();
668
  TRACE (_T("CdlLoadWarning: %s\n"), pDoc->m_strCdlErrorMessage);
669
  CConfigTool::Log (CUtils::StripExtraWhitespace (pDoc->m_strCdlErrorMessage)); // display the message in the output window
670
};
671
 
672
CdlInferenceCallbackResult CConfigToolDoc::CdlGlobalInferenceHandler(CdlTransaction transaction)
673
{
674
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
675
  pDoc->m_ConflictsOutcome=NotDone;  // prepare for the case that there are no solutions
676
  CdlInferenceCallbackResult rc=CdlInferenceCallbackResult_Continue;
677
  /*
678
  std::list<CdlConflict>conflicts1(transaction->get_global_conflicts_with_solutions());
679
  const std::vector<CdlConflict>&conflicts2=transaction->get_resolved_conflicts();
680
        for (unsigned int i = 0; i < conflicts2.size (); i++) {
681
                conflicts1.push_back(conflicts2 [i]);
682
        }
683
  if(conflicts1.size()>0){
684
    CFailingRulesDialog dlg(conflicts1,transaction,&pDoc->m_arConflictsOfInterest);
685
    rc=(IDOK==dlg.DoModal())?CdlInferenceCallbackResult_Continue:CdlInferenceCallbackResult_Cancel;
686
    pDoc->m_ConflictsOutcome=(CdlInferenceCallbackResult_Continue==rc)?OK:Cancel;
687
  }
688
  */
689
  const std::list<CdlConflict>& conflicts=pDoc->GetCdlConfig()->get_all_conflicts();
690
  CFailingRulesDialog dlg(conflicts,transaction,&pDoc->m_arConflictsOfInterest);
691
  rc=(IDOK==dlg.DoModal())?CdlInferenceCallbackResult_Continue:CdlInferenceCallbackResult_Cancel;
692
  pDoc->m_ConflictsOutcome=(CdlInferenceCallbackResult_Continue==rc)?OK:Cancel;
693
 
694
  return rc;
695
}
696
 
697
CdlInferenceCallbackResult CConfigToolDoc::CdlInferenceHandler (CdlTransaction transaction)
698
{
699
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
700
  CdlInferenceCallbackResult rc=CdlInferenceCallbackResult_Continue;
701
  const std::list<CdlConflict>&conflicts=transaction->get_new_conflicts();
702
  if((pDoc->m_nRuleChecking&Immediate) && conflicts.size()>0){
703
    if(pDoc->m_nRuleChecking&SuggestFixes){
704
      std::list<CdlConflict> s_conflicts;
705
      for (std::list<CdlConflict>::const_iterator conf_i= conflicts.begin (); conf_i != conflicts.end (); conf_i++) { // for each conflict
706
        if((*conf_i)->has_known_solution()){
707
          s_conflicts.push_back(*conf_i);
708
        }
709
      }
710
      if(s_conflicts.size()>0){
711
        CFailingRulesDialog dlg(s_conflicts,transaction);
712
        return(IDOK==dlg.DoModal()?CdlInferenceCallbackResult_Continue:CdlInferenceCallbackResult_Cancel);
713
      }
714
    }
715
    CString strMsg;
716
    if(1==conflicts.size()){
717
      strMsg=(_T("There is 1 unresolved conflict."));
718
    } else {
719
      strMsg.Format(_T("There are %d unresolved conflict%s."),conflicts.size(),1==conflicts.size()?_T(""):_T("s"));
720
    }
721
    rc=(IDYES==CUtils::MessageBoxFT(MB_YESNO|MB_DEFBUTTON2,_T("%s  Make the change anyway?"),strMsg))?CdlInferenceCallbackResult_Continue:CdlInferenceCallbackResult_Cancel;
722
  }
723
  return rc;
724
}
725
 
726
 
727
// a CDL transaction handler to refresh the configuration tree
728
void CConfigToolDoc::CdlTransactionHandler (const CdlTransactionCallback & data)
729
{
730
static int nNesting=0;
731
TRACE(_T("Transaction handler: nesting level=%d\n"),nNesting++);
732
  CConfigToolDoc *pDoc=CConfigTool::GetConfigToolDoc();
733
  std::vector<CdlValuable>::const_iterator val_i;
734
  std::vector<CdlNode>::const_iterator node_i;
735
  std::list<CdlConflict>::const_iterator conf_i;
736
  CControlView *pControlView=CConfigTool::GetControlView();
737
  for (val_i = data.value_changes.begin(); val_i != data.value_changes.end(); val_i++)
738
  {
739
    const CString strName((*val_i)->get_name().c_str());
740
    TRACE(_T("%s %s : value change\n"), CString ((*val_i)->get_class_name().c_str()), strName);
741
    pControlView->Refresh(strName);
742
    if (strName==_T("CYGHWR_MEMORY_LAYOUT")){               // the memory layout has changed...
743
      pDoc->SwitchMemoryLayout (false); // ...so display a new one
744
    }
745
  }
746
  for (node_i = data.active_changes.begin(); node_i != data.active_changes.end(); node_i++)
747
  {
748
    const CString strName((*node_i)->get_name().c_str());
749
    TRACE(_T("%s %s : this has become active or inactive\n"), CString ((*node_i)->get_class_name().c_str()),
750
      CString ((*node_i)->get_name().c_str()));
751
    if (! dynamic_cast<CdlInterface> (*node_i)){ // if not an interface node
752
      pControlView->Refresh(strName);
753
    }
754
  }
755
  for (val_i = data.legal_values_changes.begin(); val_i != data.legal_values_changes.end(); val_i++)
756
  {
757
    const CString strName((*node_i)->get_class_name().c_str());
758
    TRACE(_T("%s %s : the legal_values list has changed, a new widget may be needed.\n"),
759
      CString ((*val_i)->get_class_name().c_str()), strName);
760
  }
761
 
762
  for (val_i = data.value_source_changes.begin(); val_i != data.value_source_changes.end(); val_i++)
763
  {
764
    const CString strName((*val_i)->get_name().c_str());
765
    CdlValueSource source = (*val_i)->get_source();
766
    TRACE(_T("%s %s : the value source has changed to %s\n"),
767
      CString ((*val_i)->get_class_name().c_str()), strName,
768
      CString ((CdlValueSource_Default  == source) ? "default"  :
769
    (CdlValueSource_Inferred == source) ? "inferred" :
770
    (CdlValueSource_Wizard   == source) ? "wizard"   : "user"));
771
    pControlView->Refresh (strName);
772
  }
773
 
774
  pDoc->UpdateFailingRuleCount();
775
nNesting--;
776
}
777
 
778
// Three hack functions.
779
 
780
const CString CConfigToolDoc::CurrentMemoryLayout ()
781
{
782
  const CConfigItem * pItem = Find (_T("CYGHWR_MEMORY_LAYOUT"));
783
#ifdef _DEBUG
784
  if(NULL==pItem){
785
    TRACE(_T("Warning - CurrentMemoryLayout() returning NULL\n"));
786
  }
787
#endif
788
  return pItem ? pItem->StringValue () : _T("");
789
}
790
 
791
const CString CConfigToolDoc::CurrentTestingIdentifier ()
792
{
793
  // use the CDL target as the default testing identifier
794
  // override in the forthcoming testing identifier dialog as necessary
795
  return GetCdlConfig()->get_hardware ().c_str ();
796
 
797
//  const CConfigItem * pItem = Find (_T("CYGTST_TESTING_IDENTIFIER"));
798
//#ifdef _DEBUG
799
//  if(NULL==pItem){
800
//    TRACE(_T("Warning - CurrentTestingIdentifier() returning NULL\n"));
801
//  }
802
//#endif
803
//  return pItem ? pItem->StringValue () : _T("");
804
}
805
 
806
const CString CConfigToolDoc::CurrentStartup()
807
{
808
  const CConfigItem * pItem = Find (_T("CYG_HAL_STARTUP"));
809
#ifdef _DEBUG
810
  if(NULL==pItem){
811
    TRACE(_T("Warning - CurrentStartup() returning NULL\n"));
812
  }
813
#endif
814
  return pItem ? pItem->StringValue () : _T("");
815
 
816
  /*
817
  for(int nItem=0;nItem<ItemCount();nItem++){
818
                CConfigItem *pItem=Item(nItem);
819
    const CString strName(pItem->Name());
820
    if(0==strName.Compare(_T("Startup type")) && pItem->IsEnabled()){
821
    return pItem->StringValue();
822
    }
823
    }
824
    return _T("ram"); // FIXME - assume ram startup for now if no startup item
825
  */
826
}
827
 
828
void CConfigToolDoc::UpdateFailingRuleCount()
829
{
830
  int nCount=0;
831
  if (GetCdlConfig ()){
832
    // if configuration information
833
 
834
    // calculate the number of conflicts
835
    nCount =
836
      //                GetCdlConfig ()->get_structural_conflicts ().size () +    ignore for now
837
      GetCdlConfig ()->get_all_conflicts ().size ();
838
 
839
    // update the conflicts view
840
    if (CConfigTool::GetRulesView ()) {
841
      CConfigTool::GetRulesView ()->FillRules ();
842
    }
843
  }
844
  if(CConfigTool::GetMain()){
845
    CConfigTool::GetMain()->SetFailRulePane(nCount);
846
  }
847
}
848
 
849
void CConfigToolDoc::LogConflicts (const std::list<CdlConflict> & conflicts)
850
{
851
  std::list<CdlConflict>::const_iterator conf_i;
852
  for (conf_i = conflicts.begin (); conf_i != conflicts.end (); conf_i++) // for each conflict
853
  {
854
    CString strExplain = (* conf_i)->get_explanation ().c_str (); // get the conflict explanation
855
    CConfigTool::Log (CUtils::StripExtraWhitespace (strExplain)); // display the message in the output window
856
  }
857
}
858
 
859
CString CConfigToolDoc::GetPackageName (const CString & strAlias)
860
{
861
  const std::vector<std::string> & packages = m_CdlPkgData->get_packages ();
862
  std::vector<std::string>::const_iterator package_i;
863
  for (package_i = packages.begin (); package_i != packages.end (); package_i++)
864
  {
865
    const std::vector<std::string> & aliases = m_CdlPkgData->get_package_aliases (* package_i);
866
    CString strPackageAlias = aliases [0].c_str ();
867
    if (aliases.size () && (0 == strAlias.Compare (strPackageAlias)))
868
      return package_i->c_str ();
869
  }
870
  return _T("");
871
}
872
 
873
void CConfigToolDoc::DeleteContents()
874
{
875
  TRACE(_T("###DeleteContents()\n"));
876
#ifndef PLUGIN
877
  CDocument::DeleteContents();
878
#endif
879
 
880
  RemoveAllItems();
881
  TRACE(_T("###DeleteContents done\n"));
882
}
883
 
884
void CConfigToolDoc::SelectPackages ()
885
{
886
  CCdlPackagesDialog dlg;
887
  // This map holds the CConfigItem pointers for the packages loaded before the dialog is invoked.
888
  // We cannot use Find(), which traverses all items - potentially those that have been removed
889
  CMapStringToPtr arLoadedPackages;
890
 
891
  // generate the contents of the add/remove list boxes
892
  const std::vector<std::string> & packages = m_CdlPkgData->get_packages ();
893
  std::vector<std::string>::const_iterator package_i;
894
  for (package_i = packages.begin (); package_i != packages.end (); package_i++)
895
  {
896
    //          if (! m_CdlPkgData->is_hardware_package (* package_i)) // do not list hardware packages
897
    {
898
      const std::vector<std::string> & aliases = m_CdlPkgData->get_package_aliases (* package_i);
899
      CString strMacroName = package_i->c_str ();
900
 
901
      // use the first alias (if any) as the package identifier
902
      CString strPackageName = aliases.size () ? aliases [0].c_str () : strMacroName;
903
      CConfigItem * pItem = Find (strMacroName);
904
      if (pItem) // if the package is loaded
905
      {
906
        arLoadedPackages.SetAt(strMacroName,pItem);
907
        // pass the currently selected package version string to the dialog box
908
        const CdlValuable valuable = pItem->GetCdlValuable();
909
        dlg.Insert (strPackageName, TRUE, NULL, valuable ? (LPCTSTR) CString (valuable->get_value ().c_str ()) : NULL);
910
      }
911
      else
912
      {
913
        // pass version string of the most latest version to the dialog box
914
        dlg.Insert (strPackageName, FALSE, NULL, (LPCTSTR) CString (m_CdlPkgData->get_package_versions (* package_i) [0].c_str ()));
915
      }
916
    }
917
  }
918
 
919
  if (IDOK == dlg.DoModal ())
920
  {
921
    bool bChanged = false; // until proved otherwise
922
 
923
    // determine whether each package has changed loaded/unloaded state
924
    for (package_i = packages.begin (); package_i != packages.end (); package_i++)
925
      //                        if (! m_CdlPkgData->is_hardware_package (* package_i)) // do not check hardware packages
926
    {
927
      const std::vector<std::string> & aliases = m_CdlPkgData->get_package_aliases (* package_i);
928
      CString strMacroName = package_i->c_str ();
929
 
930
      // use the first alias (if any) as the package identifier
931
      CString strPackageName = aliases.size () ? aliases [0].c_str () : strMacroName;
932
 
933
      CConfigItem *pItem=NULL;
934
      bool bPreviouslyLoaded=arLoadedPackages.Lookup(strMacroName,(void *&)pItem);
935
      bool bNowLoaded=dlg.IsAdded (strPackageName);
936
 
937
      // unload packages which are no longer required before
938
      // loading new ones to avoid potential duplicate macro definitions
939
      if (! bNowLoaded && bPreviouslyLoaded){
940
        // The package was loaded but should now be unloaded:
941
        bChanged|=pItem->Unload();
942
      } else if (bNowLoaded) {// if the package should be loaded
943
        const CString strVersion(dlg.GetVersion (strPackageName));
944
        if (bPreviouslyLoaded) { // if the package is already loaded
945
          CdlTransactionCallback::set_callback_fn (NULL); // avoid value refresh attempts during load/unload
946
          bChanged|=pItem->ChangeVersion(strVersion);
947
          CdlTransactionCallback::set_callback_fn (CdlTransactionHandler); // restore value refresh
948
        } else {
949
          // the package was not loaded but should now be loaded
950
          TRACE (_T("Loading package %s\n"), strMacroName);
951
          try
952
          {
953
            GetCdlConfig()->load_package (CUtils::UnicodeToStdStr(strMacroName), CUtils::UnicodeToStdStr (strVersion), CConfigToolDoc::CdlParseErrorHandler, CConfigToolDoc::CdlParseWarningHandler);
954
            bChanged=true;
955
          }
956
          catch (CdlStringException exception)
957
          {
958
            CUtils::MessageBoxF(_T("Error loading package %s:\n\n%s"), strMacroName, CString (exception.get_message ().c_str ()));
959
          }
960
          catch (...)
961
          {
962
            CUtils::MessageBoxF(_T("Error loading package %s."), strMacroName);
963
          }
964
        }
965
      }
966
    }
967
 
968
    if (bChanged) {// at least one package was loaded, unloaded or changed version
969
      SetModifiedFlag();
970
      RegenerateData();
971
    }
972
  }
973
}
974
 
975
bool CConfigToolDoc::SetValue(CConfigItem &ti,ItemIntegerType nValue, CdlTransaction transaction/*=NULL*/)
976
{
977
  switch(ti.Type()){
978
                case CConfigItem::Enum:
979
    case CConfigItem::Integer:
980
      //                case CConfigItem::Boolean:
981
      //                case CConfigItem::Radio:
982
      break;
983
    case CConfigItem::None:
984
    case CConfigItem::String:
985
    default:
986
      ASSERT(FALSE);
987
      break;
988
  }
989
 
990
  bool rc=false;
991
  bool bChangingMemmap=MemoryMap.map_modified () && ((ti.Macro ().Compare (_T ("CYG_HAL_STARTUP")) == 0));
992
 
993
  if(nValue==ti.Value()){
994
    return true;
995
  }
996
 
997
  // test if the new integer value is in range
998
  if (CConfigItem::Integer == ti.Type ())
999
        {
1000
    const CdlValuable valuable = ti.GetCdlValuable();
1001
    CdlListValue list_value;
1002
    CdlEvalContext context (NULL, ti.GetCdlItem (), ti.GetCdlItem ()->get_property (CdlPropertyId_LegalValues));
1003
    valuable->get_legal_values ()->eval (context, list_value);
1004
    if (! list_value.is_member ((cdl_int) nValue))
1005
    {
1006
      if (nValue==(ItemIntegerType) valuable->get_integer_value (CdlValueSource_Current) || IDNO == CUtils::MessageBoxFT (MB_YESNO, _T("%s is not a legal value for %s.\n\nDo you want to use this value anyway?"),
1007
        CUtils::IntToStr (nValue, CConfigTool::GetConfigToolDoc ()->m_bHex), ti.Macro ()))
1008
        goto Exit;
1009
    };
1010
        }
1011
 
1012
  //    if(!ti.CanSetValue(nValue))
1013
  //    {
1014
  //        if(bInteractive){
1015
  //                    CString strExplanation;
1016
  //                    if(CConfigItem::Integer==ti.Type()){
1017
  //                            strExplanation.Format(_T(" [value must lie in the range %d..%d]"),
1018
  //                                    CUtils::IntToStr(ti.Min(),m_bHex), 
1019
  //                    CUtils::IntToStr(ti.Max()),m_bHex);
1020
  //                    }
1021
  //                    CUtils::MessageBoxF(
1022
  //                            _T("Cannot set '%s' to %s%s"),
1023
  //                            ti.ItemNameOrMacro(), CUtils::IntToStr(nValue,m_bHex), strExplanation);
1024
  //        }
1025
  //            goto Exit;
1026
  //    }
1027
 
1028
  // warn the user if the current memory layout has been changed and will be lost
1029
  // this will happen when the layout has been modified and the target-platform-startup is changed
1030
 
1031
  if (bChangingMemmap && IDCANCEL==CUtils::MessageBoxFT(MB_OKCANCEL,_T("Changes to the current memory layout will be lost."))){
1032
    goto Exit;
1033
  }
1034
 
1035
  // Save state
1036
  if(!ti.SetValue(nValue,transaction)){
1037
    // CanSetValue above should have caught this
1038
    CUtils::MessageBoxF(_T("Cannot set '%s' to %d"),ti.ItemNameOrMacro(), nValue);
1039
    goto Exit;
1040
  }
1041
 
1042
  rc=true;
1043
Exit:
1044
  if(rc){
1045
    SetModifiedFlag();
1046
    UpdateFailingRuleCount ();
1047
    UpdateAllViews (NULL, CConfigToolDoc::ValueChanged, (CObject *)&ti);
1048
    // switch to new memory layout when target, platform or startup changes
1049
    // but ignore cases where a target or platform is being deactivated (PR 19363)
1050
 
1051
    //          if (((CurrentTarget () != pOldTarget) || (CurrentPlatform () != strOldPlatform) || (ti.Name ().Compare (_T ("Startup type")) == 0)) &&
1052
    //                  ((ti.Type () != CConfigItem::Radio) || (nValue)))
1053
    //                  SwitchMemoryLayout ((CurrentTarget () != pOldTarget) || (CurrentPlatform () != strOldPlatform));
1054
  }
1055
  return rc;
1056
}
1057
 
1058
bool CConfigToolDoc::OpenRepository(LPCTSTR pszRepository/*=NULL*/,bool bPromptInitially/*=false*/)
1059
{
1060
  if(!m_bRepositoryOpen){
1061
    CWaitCursor wait;
1062
    CIdleMessage IM(_T("Opening repository"));
1063
    UpdateFailingRuleCount();
1064
 
1065
    CFileName strNewRepository;
1066
    while(!m_bRepositoryOpen){
1067
 
1068
      if(bPromptInitially){
1069
        CFolderDialog dlg(/*BOOL bAllowCreation=*/false);
1070
        dlg.m_strDesc=_T("Please specify the root of the eCos repository tree.");
1071
        dlg.m_strTitle=_T("Choose folder for eCos repository");
1072
        dlg.m_strFolder=strNewRepository;
1073
        CConfigTool::DismissSplash();
1074
        if(IDCANCEL==dlg.DoModal()){
1075
          return false;
1076
        }
1077
        strNewRepository=dlg.m_strFolder;
1078
      } else {
1079
        // Use what came in as parameter or what was found in registry
1080
        strNewRepository=pszRepository?pszRepository:m_strRepository;
1081
        bPromptInitially=true;
1082
      }
1083
 
1084
      IM.Set (_T("Opening repository ") + (CString) strNewRepository);
1085
 
1086
      CdlPackagesDatabase NewCdlPkgData = NULL;
1087
      CdlInterpreter      NewCdlInterp  = NULL;
1088
      CdlConfiguration    NewCdlConfig  = NULL;
1089
      CFileName strNewPackagesDir;
1090
 
1091
      EnableCallbacks(false); // disable transaction callbacks until the config tree is regenerated
1092
 
1093
      if(OpenRepository(strNewRepository,NewCdlPkgData,NewCdlInterp,NewCdlConfig,strNewPackagesDir)){
1094
        // Success
1095
 
1096
        // select the "default" template if it exists
1097
        // otherwise select the first available template
1098
        std::string default_template = "default";
1099
        if (! NewCdlPkgData->is_known_template (default_template))
1100
        {
1101
          const std::vector<std::string>& templates = NewCdlPkgData->get_templates ();
1102
          if (templates.size () != 0)
1103
            default_template = templates [0];
1104
        }
1105
 
1106
        m_template_version = "";
1107
        try
1108
        {
1109
          const std::vector<std::string>& template_versions = NewCdlPkgData->get_template_versions (default_template);
1110
          NewCdlConfig->set_template (default_template, template_versions [0], &CdlParseErrorHandler, &CdlParseWarningHandler);
1111
          m_template_version = template_versions [0];
1112
        }
1113
        catch (CdlStringException exception) {
1114
          CUtils::MessageBoxF(_T("Error loading package template '%s':\n\n%s"), CString (default_template.c_str ()), CString (exception.get_message ().c_str ()));
1115
        }
1116
        catch (...) {
1117
          CUtils::MessageBoxF(_T("Error loading package template '%s'."), CString (default_template.c_str ()));
1118
        }
1119
 
1120
        // check the configuration
1121
        ASSERT (NewCdlConfig->check_this (cyg_extreme));
1122
 
1123
        // use the new package database, interpreter and configuration
1124
        deleteZ(m_CdlConfig); // delete the previous configuration
1125
        deleteZ(m_CdlInterp); // delete the previous interpreter
1126
        deleteZ(m_CdlPkgData); // delete the previous package database
1127
 
1128
        m_CdlPkgData = NewCdlPkgData;
1129
        m_CdlInterp  = NewCdlInterp;
1130
        m_CdlConfig  = NewCdlConfig;
1131
 
1132
        // save the repository location
1133
 
1134
        SetRepository(strNewRepository);
1135
        m_strPackagesDir = strNewPackagesDir;
1136
 
1137
#ifndef PLUGIN
1138
        // clear the previously specified document file name (if any),
1139
        // OnNewDocument() calls DeleteContents() so must be called
1140
        // before AddAllItems()
1141
        CDocument::OnNewDocument ();
1142
#endif
1143
 
1144
        // generate the CConfigItems from their CDL descriptions
1145
        AddAllItems ();
1146
 
1147
        m_bRepositoryOpen=true;
1148
      } else {
1149
        // failure
1150
        deleteZ(NewCdlConfig);
1151
        deleteZ(NewCdlInterp);
1152
        deleteZ(NewCdlPkgData);
1153
 
1154
      }
1155
 
1156
      // install a transaction handler callback function now that the tree exists
1157
      EnableCallbacks(true);
1158
    }
1159
 
1160
    }
1161
    return m_bRepositoryOpen;
1162
}
1163
 
1164
// Helper fn for namesake above
1165
bool CConfigToolDoc::OpenRepository (const CFileName strNewRepository,CdlPackagesDatabase &NewCdlPkgData,CdlInterpreter &NewCdlInterp,CdlConfiguration &NewCdlConfig,CFileName &strNewPackagesDir)
1166
{
1167
  bool rc=false;
1168
  TRACE(_T("###Open repository %s\n"),strNewRepository);
1169
  if(!strNewRepository.IsEmpty()){
1170
    // Now strNewRepository is guaranteed non-empty, but does it exist?
1171
    if(!strNewRepository.IsDir()) {
1172
      CUtils::MessageBoxF(_T("Cannot open repository - the folder %s does not exist"), strNewRepository);
1173
    } else {
1174
 
1175
      // Ok so it exists, but does it look right?
1176
      strNewPackagesDir=strNewRepository+_T("ecc");
1177
      if(!strNewPackagesDir.IsDir()){
1178
        strNewPackagesDir=strNewRepository+_T("packages");
1179
      }
1180
 
1181
      if(!strNewPackagesDir.IsDir()){
1182
        // Don't mention the ecc\ attempt
1183
        CUtils::MessageBoxF(_T("%s does not seem to be a source repository: the folder %s does not exist"),
1184
          strNewRepository,strNewPackagesDir);
1185
      } else {
1186
 
1187
        const CFileName strDatabase = strNewPackagesDir + _T("ecos.db");
1188
        if(!strDatabase.Exists()) {
1189
          CUtils::MessageBoxF(_T("%s does not seem to be a source repository: %s does not exist"), strNewRepository, strDatabase);
1190
        } else {
1191
 
1192
          // create a CDL repository, interpreter and configuration
1193
 
1194
          try {// create a new package database, interpreter and configuration
1195
            NewCdlPkgData = CdlPackagesDatabaseBody::make (CUtils::UnicodeToStdStr(strNewPackagesDir), &CdlParseErrorHandler, &CdlParseWarningHandler);
1196
            NewCdlInterp = CdlInterpreterBody::make ();
1197
            NewCdlConfig = CdlConfigurationBody::make ("eCos", NewCdlPkgData, NewCdlInterp);
1198
          }
1199
          catch (CdlStringException exception) {
1200
            CUtils::MessageBoxF(_T("Error opening eCos repository:\n\n%s"), CString (exception.get_message ().c_str ()));
1201
            return false;
1202
          }
1203
          catch (...) {
1204
            CUtils::MessageBoxF(_T("Error opening eCos repository."));
1205
            return false;
1206
          }
1207
 
1208
          // select the default target if specified in the registry
1209
          // otherwise select the first available target
1210
          std::string default_hardware = CUtils::UnicodeToStdStr (GetDefaultHardware ());
1211
          if (! NewCdlPkgData->is_known_target (default_hardware)) {
1212
            const std::vector<std::string>& targets = NewCdlPkgData->get_targets ();
1213
            if (targets.size () == 0){
1214
              CUtils::MessageBoxF (_T("Error opening eCos repository:\n\nno hardware templates"));
1215
              return false;
1216
            } else {
1217
              default_hardware = targets [0];
1218
            }
1219
          }
1220
 
1221
          try {
1222
            m_strCdlErrorMessage = _T("");
1223
            NewCdlConfig->set_hardware (default_hardware, &CdlParseErrorHandler, &CdlParseWarningHandler);
1224
          }
1225
          catch (CdlStringException exception) {
1226
            if (m_strCdlErrorMessage.IsEmpty ())
1227
            {
1228
              CUtils::MessageBoxF (_T("Error loading the default hardware template '%s':\n\n%s"), CString (default_hardware.c_str ()), CString (exception.get_message ().c_str ()));
1229
            }
1230
            else // report the most recent parser message in the message box since there may be no output pane in which to view it
1231
            {
1232
              CUtils::MessageBoxF (_T("Error loading the default hardware template '%s':\n\n%s\n\nParser message:\n\n%s"), CString (default_hardware.c_str ()), CString (exception.get_message ().c_str ()), m_strCdlErrorMessage);
1233
            }
1234
            return false;
1235
          }
1236
          catch (...) {
1237
            CUtils::MessageBoxF (_T("Error loading the default hardware template '%s':\n\n%s"), CString (default_hardware.c_str ()), m_strCdlErrorMessage);
1238
            return false;
1239
          }
1240
          rc=true;
1241
        }
1242
      }
1243
    }
1244
  }
1245
  return rc;
1246
}
1247
 
1248
void CConfigToolDoc::CloseRepository()
1249
{
1250
  if(m_bRepositoryOpen){
1251
    // delete the libCDL objects with the document
1252
    EnableCallbacks(false); // first disable the transaction handler
1253
    deleteZ(m_CdlConfig);
1254
    deleteZ(m_CdlInterp);
1255
    deleteZ(m_CdlPkgData);
1256
    m_bRepositoryOpen=false;
1257
  }
1258
}
1259
 
1260
void CConfigToolDoc::SelectTemplate (std::string NewTemplate, std::string NewTemplateVersion)
1261
{
1262
  if ((NewTemplate != m_CdlConfig->get_template()) || (NewTemplateVersion != m_template_version)){
1263
 
1264
    CWaitCursor wait; // this may take a little while
1265
    RemoveAllItems();
1266
    m_template_version = "";
1267
    try
1268
    {
1269
      m_CdlConfig->set_template (NewTemplate, NewTemplateVersion, CdlParseErrorHandler, CdlParseWarningHandler);
1270
      m_template_version = NewTemplateVersion;
1271
    }
1272
    catch (CdlStringException exception)
1273
    {
1274
      CUtils::MessageBoxF(_T("Error loading package template '%s':\n\n%s"), CString (NewTemplate.c_str ()), CString (exception.get_message ().c_str ()));
1275
    }
1276
    catch (...)
1277
    {
1278
      CUtils::MessageBoxF(_T("Error loading package template '%s'."), CString (NewTemplate.c_str ()));
1279
    }
1280
    RegenerateData();
1281
 
1282
    if (!GetPathName().IsEmpty()){ // not a new document
1283
      CopyMLTFiles (); // copy new MLT files to the build tree as necessary
1284
    }
1285
    SetModifiedFlag();
1286
  }
1287
}
1288
 
1289
void CConfigToolDoc::RegenerateData()
1290
{
1291
  CWaitCursor wait; // This may take a little while
1292
  AddAllItems (); // regenerate all the config items since the topology may have changed
1293
  if (m_strLinkerScriptFolder.IsEmpty ())
1294
  {
1295
    CUtils::MessageBoxF(_T("The eCos linker script macro CYGBLD_LINKER_SCRIPT is not defined."));
1296
  }
1297
  if (m_strMemoryLayoutFolder.IsEmpty ())
1298
  {
1299
    CUtils::MessageBoxF(_T("The eCos memory layout macro CYGHWR_MEMORY_LAYOUT is not defined."));
1300
  }
1301
  SwitchMemoryLayout (true); // the hardware template may have changed
1302
  UpdateBuildInfo();
1303
  CConfigTool::GetControlView()->SelectItem(Item(0));
1304
}
1305
 
1306
void CConfigToolDoc::SelectHardware (std::string NewTemplate)
1307
{
1308
  const std::string OldTemplate=m_CdlConfig->get_hardware();
1309
  if (NewTemplate != OldTemplate){
1310
    RemoveAllItems();
1311
 
1312
    try
1313
    {
1314
      m_CdlConfig->set_hardware (NewTemplate, CdlParseErrorHandler, CdlParseWarningHandler);
1315
    }
1316
    catch (CdlStringException exception)
1317
    {
1318
      CUtils::MessageBoxF(_T("Error loading hardware template '%s':\n\n%s"), CString (NewTemplate.c_str ()), CString (exception.get_message ().c_str ()));
1319
      m_CdlConfig->set_hardware (OldTemplate, CdlParseErrorHandler, CdlParseWarningHandler);
1320
    }
1321
    catch (...)
1322
    {
1323
      CUtils::MessageBoxF(_T("Error loading hardware template '%s'."), CString (NewTemplate.c_str ()));
1324
      m_CdlConfig->set_hardware (OldTemplate, CdlParseErrorHandler, CdlParseWarningHandler);
1325
    }
1326
 
1327
    RegenerateData();
1328
    //EnableCallbacks(true); // re-enable the transaction handler
1329
    if (!GetPathName().IsEmpty()){
1330
      CopyMLTFiles (); // copy new MLT files to the build tree as necessary
1331
    }
1332
    SetModifiedFlag();
1333
  }
1334
}
1335
 
1336
bool CConfigToolDoc::SaveMemoryMap()
1337
{
1338
  const CString strSuffix(_T("mlt_") + CurrentMemoryLayout ());
1339
  const CFileName strMLTInstallPkgconfDir(InstallTree() + _T("include\\pkgconf"));
1340
  bool rc=false;
1341
  if(strMLTInstallPkgconfDir.CreateDirectory(true)){
1342
    const CString strMLTInstallBase(strMLTInstallPkgconfDir+CFileName(strSuffix));
1343
    const CFileName strMLTDir (MLTDir());
1344
    if(strMLTDir.CreateDirectory (true)){
1345
      const CString strMLTBase (strMLTDir + CFileName (strSuffix));
1346
      TRACE(_T("Saving memory layout to %s\n"), strMLTBase + _T(".mlt"));
1347
      if(MemoryMap.save_memory_layout (strMLTBase + _T(".mlt"))){
1348
        TRACE(_T("Exporting memory layout to %s\n"), strMLTInstallPkgconfDir);
1349
        rc=MemoryMap.export_files (strMLTInstallBase + _T(".ldi"), strMLTInstallBase + _T(".h"));
1350
      }
1351
    }
1352
  }
1353
  return rc;
1354
}
1355
 
1356
bool CConfigToolDoc::CopyMLTFiles()
1357
{
1358
  // copy default MLT files for the selected target/platform from the repository if they do not already exist
1359
 
1360
  TRACE (_T("Looking for MLT files at %s\n"), PackagesDir() + m_strMemoryLayoutFolder + _T("include\\pkgconf\\mlt_*.*"));
1361
  const CFileName strInstallDestination(InstallTree () + _T("include\\pkgconf"));
1362
  const CFileName strMLTDestination (MLTDir ());
1363
  TRACE (_T("Copying .ldi and .h files to %s\n"), strInstallDestination);
1364
  TRACE (_T("Copying .mlt files to %s\n"), strMLTDestination);
1365
  bool rc=strInstallDestination.CreateDirectory (true) && strMLTDestination.CreateDirectory (true);
1366
  if(rc){
1367
    CFileFind ffFileFind;
1368
    BOOL bLastFile = ffFileFind.FindFile (PackagesDir() + m_strMemoryLayoutFolder + _T("\\include\\pkgconf\\mlt_*.*"));
1369
    while (bLastFile)
1370
    {
1371
      bLastFile = ffFileFind.FindNextFile ();
1372
      if (_T(".mlt") == ffFileFind.GetFileName ().Right (4)) // if a .mlt file
1373
      {
1374
        if (! CFileName (strMLTDestination, CFileName (ffFileFind.GetFileName ())).Exists ())
1375
        {
1376
          if(!CUtils::CopyFile (ffFileFind.GetFilePath (), strMLTDestination + CFileName (ffFileFind.GetFileName ()))){
1377
            return false; // message already emitted
1378
          }
1379
        }
1380
      }
1381
      else // a .h or .ldi file
1382
      {
1383
        if (! CFileName (strInstallDestination, CFileName (ffFileFind.GetFileName ())).Exists () &&
1384
          !CUtils::CopyFile (ffFileFind.GetFilePath (), strInstallDestination + CFileName (ffFileFind.GetFileName ()))){
1385
          return false; // message already emitted
1386
        }
1387
      }
1388
    }
1389
  }
1390
  return rc; //FIXME
1391
}
1392
 
1393
CString CConfigToolDoc::GetDefaultHardware ()
1394
{
1395
  CString strKey = _T("SOFTWARE\\Red Hat\\eCos");
1396
  CString strVersionKey = _T("");
1397
  CString rc = _T("");
1398
  TCHAR pszBuffer [MAX_PATH + 1];
1399
  HKEY hKey;
1400
  LONG lStatus;
1401
 
1402
  // get the greatest eCos version subkey
1403
  if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, strKey, 0L, KEY_READ, &hKey))
1404
  {
1405
    DWORD dwIndex = 0;
1406
    while (ERROR_SUCCESS == RegEnumKey (hKey, dwIndex++, (LPTSTR) pszBuffer, sizeof (pszBuffer)))
1407
    {
1408
      if (strVersionKey.Compare (pszBuffer) < 0)
1409
        strVersionKey = pszBuffer;
1410
    }
1411
    RegCloseKey (hKey);
1412
    if (! strVersionKey.IsEmpty ())
1413
    {
1414
      TRACE (_T("CConfigToolDoc::GetDefaultHardware(): version subkey = '%s'\n"), strVersionKey);
1415
 
1416
      // get the default hardware value
1417
      strKey +=  _T("\\") + strVersionKey;
1418
      if (ERROR_SUCCESS == RegOpenKeyEx (HKEY_LOCAL_MACHINE, strKey, 0L, KEY_READ, &hKey))
1419
      {
1420
        DWORD dwBufferSize = sizeof (pszBuffer);
1421
        lStatus = RegQueryValueEx (hKey, _T("Default Hardware"), NULL, NULL, (LPBYTE) pszBuffer, &dwBufferSize);
1422
        RegCloseKey (hKey);
1423
        if (ERROR_SUCCESS == lStatus)
1424
        {
1425
          TRACE (_T("CConfigToolDoc::GetDefaultHardware(): default hardware = '%s'\n"), pszBuffer);
1426
          rc=pszBuffer;
1427
        }
1428
      }
1429
    }
1430
  }
1431
  return rc;
1432
}
1433
 
1434
CConfigItem * CConfigToolDoc::AddItem (const CdlUserVisible vitem, CConfigItem * pParent)
1435
{
1436
  CConfigItem * pItem = new CConfigItem (pParent, vitem);
1437
 
1438
  m_arItem.Add(pItem);
1439
  pItem->m_strDesc = CUtils::StripExtraWhitespace (CString (vitem->get_description ().c_str ()));
1440
 
1441
  if (vitem->get_name () == "CYGHWR_MEMORY_LAYOUT")
1442
  {
1443
    ASSERT (m_strMemoryLayoutFolder.IsEmpty ());
1444
    m_strMemoryLayoutFolder = vitem->get_owner ()->get_directory().c_str ();
1445
    m_strMemoryLayoutFolder.Replace(_TCHAR('/'),_TCHAR('\\'));
1446
    TRACE (_T("Found memory layout folder: %s\n"), m_strMemoryLayoutFolder);
1447
  }
1448
 
1449
  if (vitem->get_name () == "CYGBLD_LINKER_SCRIPT")
1450
  {
1451
    ASSERT (m_strLinkerScriptFolder.IsEmpty ());
1452
    m_strLinkerScriptFolder = vitem->get_owner ()->get_directory().c_str ();
1453
    m_strLinkerScriptFolder.Replace(_TCHAR('/'),_TCHAR('\\'));
1454
    TRACE (_T("Found linker script folder: %s\n"), m_strLinkerScriptFolder);
1455
 
1456
    // the CDL hardware template name will eventually become the target name,
1457
    // but for now we must deduce the target name from the linker script file name
1458
 
1459
    const CdlValuable valuable = dynamic_cast<CdlValuable> (vitem);
1460
    CFileName strLinkerScript (m_strPackagesDir, m_strLinkerScriptFolder, CString (valuable->get_value ().c_str ()));
1461
    strLinkerScript.Replace (_TCHAR('/'), _TCHAR('\\'));
1462
    if(!strLinkerScript.Exists ()){
1463
        CConfigTool::Log(_T("%s does not exist\n"),strLinkerScript);
1464
    }
1465
    TRACE (_T("Target '%s' selected\n"), strLinkerScript.Tail ().Root (), pItem->Macro());
1466
    //CFileName strBinDir = AfxGetApp () -> GetProfileString (CUtils::LoadString (IDS_KEY_TOOLS_DIR), pTarget->Name (), _T(""));
1467
    //if (! strBinDir.IsEmpty () && strBinDir.IsDir ())
1468
    //{
1469
    //  pTarget->SetBinDir (strBinDir);
1470
    //}
1471
  }
1472
 
1473
  //TRACE(_T("Created new item from cdl: "));
1474
  //pItem->DumpItem();
1475
  return pItem;
1476
}
1477
 
1478
void CConfigToolDoc::AddAllItems ()
1479
{
1480
  // remove any old items and packages
1481
  DeleteContents ();
1482
  if(NULL!=CConfigTool::GetControlView()){ // may not be the case for plugin
1483
 
1484
    // add the root item
1485
    CConfigItem * pItem = new CConfigItem (NULL, NULL);
1486
    m_arItem.Add(pItem);
1487
    pItem->m_strDesc = _T("The root node for all configurable items");
1488
 
1489
    // add the remaining items using their CDL descriptions
1490
    m_strMemoryLayoutFolder = _T("");
1491
    m_strLinkerScriptFolder = _T("");
1492
    AddContents (m_CdlConfig, FirstItem ());
1493
 
1494
    // check that exactly one radio button in each group is enabled
1495
    CheckRadios ();
1496
 
1497
    // update the rules (conflicts) view
1498
    UpdateFailingRuleCount ();
1499
 
1500
    if(NULL==CConfigTool::GetRulesView() || !CConfigTool::GetRulesView()->IsWindowVisible()){
1501
      // log all conflicts
1502
      //        LogConflicts (m_CdlConfig->get_structural_conflicts ()); // relating to package availability - ignore for now
1503
      LogConflicts (m_CdlConfig->get_all_conflicts ());
1504
    }
1505
 
1506
    CConfigTool::GetControlView()->SelectItem(Item(0));
1507
    UpdateAllViews (NULL, SelChanged, (CObject *)Item(0)); // refresh the display
1508
    if(ItemCount()>0){
1509
      CConfigTool::GetControlView()->GetTreeCtrl().Expand(Item(0)->HItem(),TVE_EXPAND);
1510
    }
1511
    CConfigTool::GetControlView()->SetFocus();
1512
  }
1513
}
1514
 
1515
const CFileName CConfigToolDoc::CurrentLinkerScript()
1516
{
1517
  const CConfigItem * pItem = Find (_T("CYGBLD_LINKER_SCRIPT"));
1518
  return pItem ? CFileName (m_strPackagesDir, m_strLinkerScriptFolder, pItem->StringValue ()) : _T("");
1519
}
1520
 
1521
bool CConfigToolDoc::GenerateHeaders()
1522
{
1523
// Copy non-config header files from the repository to the
1524
// install tree for plugin only. The make system used by
1525
// the standalone config tool does this for us.
1526
#ifdef PLUGIN
1527
  typedef std::vector<CdlBuildInfo_Loadable> EntriesArray;
1528
  const EntriesArray &arEntries=BuildInfo().entries;
1529
  typedef std::vector<CdlBuildInfo_Header> HeaderArray;
1530
  for(EntriesArray::size_type j=0;j<arEntries.size();j++){
1531
    const CdlBuildInfo_Loadable &e=arEntries[j];
1532
    const CFileName strDir(CUtils::WPath(e.directory));
1533
    const HeaderArray &arHeaders=e.headers;
1534
    for(HeaderArray::size_type i=0;i<arHeaders.size();i++){
1535
      const CdlBuildInfo_Header &h=arHeaders[i];
1536
      const CFileName strSource(PackagesDir()+strDir+CUtils::WPath(h.source));
1537
      const CFileName strDest(HeadersDir()/*+CUtils::WPath(e.directory)*/+CUtils::WPath(h.destination));
1538
 
1539
      if(!strDest.Head().CreateDirectory(true)){
1540
        CUtils::MessageBoxF(_T("Failed to create %s - %s"),strDest.Head(),CUtils::GetLastErrorMessageString());
1541
        return false;
1542
      }
1543
      if(!CUtils::CopyFile(strSource,strDest)){
1544
        return false; // message already emitted
1545
      }
1546
    }
1547
  }
1548
#endif
1549
 
1550
  // Generate headers
1551
  try {
1552
    CFileName strPkfConfDir(InstallTree()+_T("include\\pkgconf"));
1553
    if(!strPkfConfDir.CreateDirectory()){
1554
      CUtils::MessageBoxF(_T("Failed to create %s - %s"),strPkfConfDir,CUtils::GetLastErrorMessageString());
1555
      return false;
1556
    }
1557
    GetCdlConfig()->generate_config_headers(CUtils::UnicodeToStdStr(strPkfConfDir.ShortName()));
1558
  }
1559
  catch (CdlInputOutputException e) {
1560
    const CString strMsg(e.get_message().c_str());
1561
    TRACE(_T("!!! Exception thrown calling generate_config_headers - %s"),strMsg);
1562
    CUtils::MessageBoxF(_T("Failed to generate header files - %s"),strMsg);
1563
    return false;
1564
  }
1565
  return true;
1566
}
1567
 
1568
const CFileName CConfigToolDoc::MLTDir ()
1569
{
1570
        CString strPathName (GetPathName ());
1571
        ASSERT (! strPathName.IsEmpty ());
1572
        return strPathName.Left (strPathName.ReverseFind (_TCHAR('.'))) + _T("_mlt");
1573
}
1574
 
1575
bool CConfigToolDoc::UpdateBuildInfo(bool bFirstTime)
1576
{
1577
  try {
1578
    GetCdlConfig()->get_build_info(m_BuildInfo);
1579
    #ifdef PLUGIN
1580
    // FIXME: this means anything not mentioned by AddFile in our scan below will be removed - including user-added items
1581
    m_peCosProject->ClearItemFlags();
1582
    m_peCosProject->UpdateeCosProject(bFirstTime);
1583
    m_peCosProject->RemoveAllUnflaggedItems();
1584
    #else
1585
    UNUSED_ALWAYS(bFirstTime);
1586
    generate_build_tree (GetCdlConfig(), CUtils::UnicodeToStdStr(BuildTree()), CUtils::UnicodeToStdStr(InstallTree()));
1587
    #endif
1588
    return true;
1589
  }
1590
  catch(...){
1591
    return false;
1592
  }
1593
}
1594
 
1595
void CConfigToolDoc::RemoveAllItems()
1596
{
1597
  for(int nItem=0;nItem<ItemCount();nItem++){
1598
    CConfigItem *pItem=Item(nItem);
1599
    deleteZ(pItem);
1600
  }
1601
  m_arItem.RemoveAll();
1602
 
1603
  UpdateAllViews(NULL,Clear,0);
1604
}
1605
 
1606
void CConfigToolDoc::EnableCallbacks (bool bEnable/*=true*/)
1607
{
1608
  CdlTransactionCallback::set_callback_fn(bEnable?&CdlTransactionHandler:0);
1609
  CdlTransactionBody::set_inference_callback_fn(bEnable?&CdlInferenceHandler:0);
1610
  CdlTransactionBody::set_inference_override(CdlValueSource_Invalid);
1611
}
1612
 
1613
int CConfigToolDoc::GetTestExeNames (CFileNameArray &arTestExes,CFileNameArray &arMissing)
1614
{
1615
  arTestExes.RemoveAll();
1616
  arMissing.RemoveAll();
1617
 
1618
  typedef std::vector<CdlBuildInfo_Loadable> EntriesArray;
1619
  const EntriesArray &arEntries=BuildInfo().entries;
1620
  for(EntriesArray::size_type j=0;j<arEntries.size();j++){
1621
    const CdlBuildInfo_Loadable &e=arEntries[j];
1622
    CStringArray ar;
1623
    int n=CUtils::Chop(CString(get_tests(GetCdlConfig(),e).c_str()),ar);
1624
    for(int i=0;i<n;i++){
1625
      CFileName strFile;
1626
      strFile.Format(_T("%s\\tests\\%s\\%s.exe"),InstallTree(),CString(e.directory.c_str()),ar[i]);
1627
      strFile.Replace(_TCHAR('/'),_TCHAR('\\'));
1628
      if(strFile.Exists()){
1629
        arTestExes.Add(strFile);
1630
      } else {
1631
        arMissing.Add(strFile);
1632
      }
1633
    }
1634
  }
1635
  return arTestExes.GetSize();
1636
}
1637
 
1638
CConfigToolDoc::GlobalConflictOutcome CConfigToolDoc::ResolveGlobalConflicts(CPtrArray *parConflictsOfInterest)
1639
{
1640
  m_ConflictsOutcome=NotDone;
1641
  m_arConflictsOfInterest.RemoveAll();
1642
  if(parConflictsOfInterest){
1643
    m_arConflictsOfInterest.Copy(*parConflictsOfInterest);
1644
  }
1645
  CdlInferenceCallback fn=CdlTransactionBody::get_inference_callback_fn();
1646
  CdlTransactionBody::set_inference_callback_fn(CdlGlobalInferenceHandler);
1647
  GetCdlInterpreter()->get_toplevel()->resolve_all_conflicts();
1648
  CdlTransactionBody::set_inference_callback_fn(fn);
1649
  if(NotDone==m_ConflictsOutcome){
1650
    // No solutions were available, but we'll run the dialog anyway
1651
    const std::list<CdlConflict>& conflicts=GetCdlConfig()->get_all_conflicts();
1652
    CFailingRulesDialog dlg(conflicts,NULL,&m_arConflictsOfInterest);
1653
    m_ConflictsOutcome=(IDOK==dlg.DoModal())?OK:Cancel;
1654
  }
1655
  return m_ConflictsOutcome;
1656
}
1657
 
1658
bool CConfigToolDoc::CheckConflictsBeforeSave()
1659
{
1660
  if(GetCdlInterpreter()->get_toplevel()->get_all_conflicts().size()>0){
1661
    if(Deferred&m_nRuleChecking){
1662
      if((SuggestFixes&m_nRuleChecking)&&(Cancel==ResolveGlobalConflicts())){
1663
        return false;
1664
      }
1665
      int nConflicts=GetCdlInterpreter()->get_toplevel()->get_all_conflicts().size();
1666
      switch(nConflicts){
1667
      case 0:
1668
        break;
1669
      case 1:
1670
        if(IDNO==CUtils::MessageBoxFT(MB_YESNO|MB_DEFBUTTON2,_T("There is 1 unresolved conflict.  Save anyway?"))){
1671
          return false;
1672
        }
1673
      default:
1674
        if(IDNO==CUtils::MessageBoxFT(MB_YESNO|MB_DEFBUTTON2,_T("There are %d unresolved conflicts.  Save anyway?"),nConflicts)){
1675
          return false;
1676
        }
1677
      }
1678
    }
1679
  }
1680
  return true;
1681
}
1682
 
1683
BOOL CConfigToolDoc::IsModified()
1684
{
1685
  return m_bModified || MemoryMap.map_modified();
1686
}
1687
 
1688
void CConfigToolDoc::OnFileExport()
1689
{
1690
  CFileDialog dlg (FALSE, _T("ecm"), NULL, OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY, _T("eCos Minimal Configuration (*.ecm)|*.ecm||"), AfxGetMainWnd ());
1691
  TCHAR szBuffer [MAX_PATH * 16] = _T("");
1692
  dlg.m_ofn.lpstrFile = szBuffer;
1693
  dlg.m_ofn.nMaxFile = MAX_PATH * 16;
1694
  dlg.m_ofn.lpstrTitle = _T("Export eCos Minimal Configuration");
1695
  if (IDOK == dlg.DoModal ()) {
1696
    try {
1697
      TRACE (_T("Exporting eCos minimal configuration '%s'\n"), dlg.GetPathName ());
1698
      m_CdlConfig->save (CUtils::UnicodeToStdStr (dlg.GetPathName ()), /* minimal = */ true);
1699
    }
1700
    catch (CdlStringException exception) {
1701
      CUtils::MessageBoxF (_T("Error exporting eCos minimal configuration:\n\n%s"), CString (exception.get_message ().c_str ()));
1702
    }
1703
    catch (...) {
1704
      CUtils::MessageBoxF (_T("Error exporting eCos minimal configuration."));
1705
    }
1706
  }
1707
}
1708
 
1709
void CConfigToolDoc::OnFileImport()
1710
{
1711
  CFileDialog dlg (TRUE, _T("ecm"), NULL, OFN_PATHMUSTEXIST | OFN_HIDEREADONLY, _T("eCos Minimal Configurations (*.ecm)|*.ecm||"), AfxGetMainWnd ());
1712
  TCHAR szBuffer [MAX_PATH * 16] = _T("");
1713
  dlg.m_ofn.lpstrFile = szBuffer;
1714
  dlg.m_ofn.nMaxFile = MAX_PATH * 16;
1715
  dlg.m_ofn.lpstrTitle = _T("Import eCos Minimal Configuration");
1716
  if (IDOK == dlg.DoModal ()) {
1717
    try {
1718
      TRACE (_T("Importing eCos minimal configuration '%s'\n"), dlg.GetPathName ());
1719
      m_CdlConfig->add (CUtils::UnicodeToStdStr (dlg.GetPathName ()), CConfigToolDoc::CdlParseErrorHandler, CConfigToolDoc::CdlParseWarningHandler);
1720
    }
1721
    catch (CdlStringException exception) {
1722
      CUtils::MessageBoxF (_T("Error importing eCos minimal configuration:\n\n%s"), CString (exception.get_message ().c_str ()));
1723
    }
1724
    catch (...) {
1725
      CUtils::MessageBoxF (_T("Error importing eCos minimal configuration."));
1726
    }
1727
 
1728
    CWaitCursor wait;
1729
    AddAllItems (); // regenerate all the config items since the topology may have changed
1730
    if (m_strLinkerScriptFolder.IsEmpty ()) {
1731
      CUtils::MessageBoxF (_T("The eCos linker script macro CYGBLD_LINKER_SCRIPT is not defined."));
1732
    }
1733
    if (m_strMemoryLayoutFolder.IsEmpty ()) {
1734
      CUtils::MessageBoxF (_T("The eCos memory layout macro CYGHWR_MEMORY_LAYOUT is not defined."));
1735
    }
1736
    SwitchMemoryLayout (true); // the hardware template may have changed
1737
    UpdateBuildInfo ();
1738
    CConfigTool::GetControlView()->SelectItem (Item (0));
1739
    SetModifiedFlag ();
1740
  }
1741
}
1742
 
1743
bool CConfigToolDoc::QualifyDocURL(CString &strURL)
1744
{
1745
  if(-1==strURL.Find(_T("://"))){
1746
    strURL.Replace(_TCHAR('/'),_TCHAR('\\'));
1747
    if (! CFileName (strURL).IsFile ()) { // if not an absolute filepath
1748
      strURL = DocBase () + CFileName (strURL); // prepend the doc directory path
1749
    }
1750
    strURL=_T("file://")+strURL;
1751
  }
1752
 
1753
  if(0==strURL.Find(_T("file://"))){
1754
    CFileName strFile(strURL.Right(strURL.GetLength()-7));
1755
    int nIndex=strFile.ReverseFind(_TCHAR('#'));
1756
    if(-1!=nIndex){
1757
      strFile=strFile.Left(nIndex);
1758
    }
1759
    strFile.Replace(_TCHAR('/'),_TCHAR('\\'));
1760
    if(!strFile.Exists()){
1761
      CUtils::MessageBoxF(_T("Cannot locate the file %s"),strFile);
1762
      return false;
1763
    }
1764
  }
1765
  return true;
1766
}
1767
 
1768
bool CConfigToolDoc::NewMemoryLayout (const CString &strPrefix)
1769
{
1770
  CFileName strFileName = CurrentLinkerScript ();
1771
  TRACE(_T("Reading linker-defined memory sections from %s\n"), strFileName);
1772
  MemoryMap.new_memory_layout (); // delete the old memory layout regardless
1773
  if (! strFileName.IsEmpty ())
1774
    MemoryMap.import_linker_defined_sections (strFileName); // read the linker-defined section names from the repository (failure is silent)
1775
 
1776
  CString strMemoryLayoutFileName = strPrefix + _T("\\mlt_") + CurrentMemoryLayout () + _T(".mlt");
1777
  TRACE(_T("Reading memory layout from %s\n"), strMemoryLayoutFileName);
1778
  MemoryMap.load_memory_layout (strMemoryLayoutFileName); // load the new memory layout (failure is silent)
1779
  strSelectedSection = _T("");
1780
  strSelectedRegion = _T("");
1781
  UpdateAllViews (NULL, MemLayoutChanged);
1782
  return true; // FIXME
1783
}
1784
 
1785
void CConfigToolDoc::SetPathName( LPCTSTR pszPath, BOOL bAddToMRU /*= TRUE*/ )
1786
{
1787
  if(_TCHAR('\0')==*pszPath){ // called like this after failed saves to put things back as they were
1788
          // CDocument::SetPathName would assert given an empty string
1789
          m_strPathName = _T("");
1790
#ifndef PLUGIN
1791
    SetTitle(_T("Untitled"));
1792
#endif
1793
    m_strBuildTree   = _T("");
1794
    m_strInstallTree = _T("");
1795
  } else {
1796
#ifdef PLUGIN
1797
    m_strPathName = CFileName (pszPath);
1798
#else
1799
    CDocument::SetPathName (pszPath, bAddToMRU);
1800
#endif
1801
    CString strFolder (pszPath);
1802
    strFolder = strFolder.Left (strFolder.ReverseFind (_TCHAR('.'))); // extract folder from file path
1803
    m_strBuildTree   = CFileName(strFolder + _T("_build"));
1804
    m_strInstallTree = CFileName(strFolder + _T("_install"));
1805
  }
1806
}
1807
 
1808
bool CConfigToolDoc::ShowHtmlHelp (LPCTSTR pszURL)
1809
{
1810
 
1811
  HWND hwndCaller=AfxGetMainWnd()->CWnd::GetDesktopWindow()->GetSafeHwnd();
1812
  bool rc=false;
1813
  const CFileName strFile(HTMLHelpLinkFileName());
1814
  CStdioFile f;
1815
  if(!CFileName(CConfigTool::strHelpFile).Exists()) {
1816
    CUtils::MessageBoxF(_T("Cannot display help - %s does not exist\n"),CConfigTool::strHelpFile);
1817
  } else if(!f.Open(strFile,CFile::typeText|CFile::modeCreate|CFile::modeWrite)){
1818
    CUtils::MessageBoxF(_T("Cannot display help - error creating %s\n"),strFile);
1819
  } else {
1820
    CString str;
1821
    str.Format(_T("<meta HTTP-EQUIV=\"refresh\" CONTENT=\"0;URL=%s\">"),pszURL);
1822
    f.WriteString(str);
1823
    f.Close();
1824
    if(0==HtmlHelp(hwndCaller, CConfigTool::strHelpFile, HH_DISPLAY_TOPIC, 0)){
1825
      CUtils::MessageBoxF(_T("Cannot display %s"),pszURL);
1826
    } else {
1827
      // FIXME: Do this the first time only?
1828
      HH_WINTYPE WinType;
1829
      HWND wnd;
1830
      HH_WINTYPE *pWinType=NULL;
1831
      wnd = HtmlHelp(hwndCaller, CConfigTool::strHelpFile+_T(">mainwin"), HH_GET_WIN_TYPE, (DWORD) &pWinType);
1832
      WinType=*pWinType;
1833
      WinType.hwndCaller=hwndCaller;
1834
      WinType.fsWinProperties|=HHWIN_PROP_TRACKING;
1835
      WinType.idNotify = ID_HHNOTIFICATION;
1836
      wnd = HtmlHelp(hwndCaller, CConfigTool::strHelpFile, HH_SET_WIN_TYPE, (DWORD) &WinType);
1837
      rc=true;
1838
    }
1839
    //::DeleteFile(strFile);
1840
  }
1841
  return rc;
1842
}
1843
 
1844
const CString CConfigToolDoc::HTMLHelpLinkFileName()
1845
{
1846
  return CFileName(CConfigTool::strHelpFile).Head()+"link2.htm";
1847
}

powered by: WebSVN 2.1.0

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