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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-3.0/] [host/] [tools/] [Utils/] [win32/] [CTUtils.cpp] - Blame information for rev 786

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
//
23
//===========================================================================
24
//===========================================================================
25
//#####DESCRIPTIONBEGIN####
26
//
27
// Author(s):   sdf
28
// Contact(s):  sdf
29
// Date:                1998/08/11
30
// Version:             0.01
31
// Purpose:     
32
// Description: This is a collection of utility functions.
33
// Requires:    
34
// Provides:    
35
// See also:    
36
// Known bugs:  
37
// Usage:       
38
//
39
//####DESCRIPTIONEND####
40
//
41
//===========================================================================
42
#include "stdafx.h"
43
#include "CTUtils.h"
44
 
45
#include <float.h> // for DBL_DIG macro
46
#include <sys/types.h>
47
#include <sys/stat.h>
48
 
49
#define INCLUDEFILE <string>
50
#include "IncludeSTL.h"
51
 
52
// Chop str into pieces, using cSep as separator.
53
// " and \ have usual semantics
54
// Return value is array of pieces found.
55
 
56
int CUtils::Chop(LPCTSTR psz,CStringArray &ar,TCHAR cSep,bool bObserveStrings/*=false*/,bool bBackslashQuotes/*=false*/)
57
{
58
  if(_TCHAR(' ')==cSep){
59
    return Chop(psz,ar,_T("\t\n\v\f\r "),bObserveStrings,bBackslashQuotes);
60
  } else {
61
    ASSERT(_TCHAR('\0')!=cSep);
62
    TCHAR c[2]={cSep,_TCHAR('\0')};
63
    return Chop(psz,ar,c,bObserveStrings,bBackslashQuotes);
64
  }
65
}
66
 
67
int CUtils::Chop(LPCTSTR psz,CStringArray &ar,LPCTSTR pszSep,bool bObserveStrings/*=false*/,bool bBackslashQuotes/*=false*/)
68
{
69
        ar.RemoveAll();
70
        int i=0;
71
        for(;;){
72
                // Skip multiple separators
73
    while(*psz&&_tcschr(pszSep,*psz)){
74
      psz++;
75
    }
76
                if(!*psz){
77
                        return i;
78
                }
79
                CString strTok;
80
                if(bObserveStrings){
81
                        BOOL bInString=FALSE;
82
                        do{
83
                                if(*psz==_TCHAR('\\') && bBackslashQuotes && psz[1]){
84
                                        strTok+=psz[1];
85
                                        psz++;
86
                                } else if(*psz==_TCHAR('"')){
87
                                        bInString ^= 1;
88
                                } else if (!bInString && *psz && NULL!=_tcschr(pszSep,*psz)) {
89
                                        break;
90
                                } else {
91
                                        strTok+=*psz;
92
                                }
93
                        } while (*++psz);
94
                } else {
95
      LPCTSTR pszStart=psz;
96
                        do {
97
        psz++;
98
                        } while (*psz && !_tcschr(pszSep,*psz));
99
      strTok=CString(pszStart,psz-pszStart);
100
                }
101
                ar.SetAtGrow(i++,strTok);
102
        }
103
    return ar.GetSize();
104
}
105
 
106
 
107
// vararg-style message box formatter
108
int CUtils::MessageBoxF (LPCTSTR pszFormat, ...)
109
{
110
  int rc;
111
  va_list args;
112
  va_start(args, pszFormat);
113
  rc=CUtils::vMessageBox(MB_OK, pszFormat,args);
114
  va_end(args);
115
  return rc;
116
}
117
 
118
// As above, but with type as first parameter.
119
int CUtils::MessageBoxFT (UINT nType, LPCTSTR pszFormat, ...)
120
{
121
  int rc;
122
  va_list args;
123
  va_start(args, pszFormat);
124
  rc=CUtils::vMessageBox(nType, pszFormat,args);
125
  va_end(args);
126
  return rc;
127
}
128
 
129
int CUtils::vMessageBox(UINT nType, LPCTSTR  pszFormat, va_list marker)
130
{
131
  int rc=0;
132
  for(int nLength=100;nLength;) {
133
    TCHAR *buf=new TCHAR[1+nLength];
134
    int n=_vsntprintf(buf, nLength, pszFormat, marker );
135
    if(-1==n){
136
      nLength*=2;  // NT behavior
137
    } else if (n<nLength){
138
      rc=AfxMessageBox(buf,nType);
139
      nLength=0;   // trigger exit from loop
140
    } else {
141
      nLength=n+1; // UNIX behavior generally, or NT behavior when buffer size exactly matches required length
142
    }
143
    delete [] buf;
144
  }
145
  return rc;
146
}
147
 
148
 
149
BOOL CUtils::StrToItemIntegerType(const CString & str,__int64 &d)
150
{
151
        extern int errno;
152
        PTCHAR pEnd;
153
        BOOL rc;
154
        errno=0;
155
        BOOL bHex=(str.GetLength()>2 && str[0]==_TCHAR('0') && (str[1]==_TCHAR('x')||str[1]==_TCHAR('X')));
156
        d=_tcstol(str,&pEnd,bHex?16:10);
157
        rc=(0==errno && (*pEnd==_TCHAR('\0')));
158
        return rc;
159
}
160
 
161
const CString CUtils::IntToStr(__int64 d,bool bHex)
162
{
163
  CString s;
164
  s.Format(bHex?_T("0x%08x"):_T("%d"),d);
165
  return s;
166
}
167
 
168
const CString CUtils::DoubleToStr (double dValue)
169
{
170
  CString s;
171
  s.Format (_T("%.*e"), DBL_DIG, dValue);
172
  return s;
173
}
174
 
175
BOOL CUtils::StrToDouble (const CString & strValue, double &dValue)
176
{
177
        extern int errno;
178
        PTCHAR pEnd;
179
        errno = 0;
180
        dValue = _tcstod (strValue, &pEnd);
181
        return (0 == errno) && (*pEnd == _TCHAR('\0'));
182
}
183
 
184
const CString CUtils::Explanation(CFileException & exc)
185
{
186
        CString strMsg;
187
        switch(exc.m_cause){
188
                case CFileException::none: strMsg=_T("No error occurred.");break;
189
                case CFileException::generic: strMsg=_T("   An unspecified error occurred.");break;
190
                case CFileException::fileNotFound: strMsg=_T("   The file could not be located.");break;
191
                case CFileException::badPath: strMsg=_T("   All or part of the path is invalid.");break;
192
                case CFileException::tooManyOpenFiles: strMsg=_T("   The permitted number of open files was exceeded.");break;
193
                case CFileException::accessDenied: strMsg=_T("   The file could not be accessed.");break;
194
                case CFileException::invalidFile: strMsg=_T("   There was an attempt to use an invalid file handle.");break;
195
                case CFileException::removeCurrentDir: strMsg=_T("   The current working directory cannot be removed.");break;
196
                case CFileException::directoryFull: strMsg=_T("   There are no more directory entries.");break;
197
                case CFileException::badSeek: strMsg=_T("   There was an error trying to set the file pointer.");break;
198
                case CFileException::hardIO: strMsg=_T("   There was a hardware error.");break;
199
                case CFileException::sharingViolation: strMsg=_T("   SHARE.EXE was not loaded, or a shared region was locked.");break;
200
                case CFileException::lockViolation: strMsg=_T("   There was an attempt to lock a region that was already locked.");break;
201
                case CFileException::diskFull: strMsg=_T("   The disk is full.");break;
202
                case CFileException::endOfFile: strMsg=_T("   The end of file was reached. ");break;
203
                default:
204
                        strMsg=_T(" Unknown cause");
205
                        break;
206
        }
207
        return strMsg;
208
}
209
 
210
 
211
const CString CUtils::LoadString(UINT id)
212
{
213
        CString str;
214
        str.LoadString(id);
215
        return str;
216
}
217
 
218
bool CUtils::AddToPath(const CFileName & strFolder, bool bAtFront)
219
{
220
        CString strPath,strOldPath;
221
        int nSize=GetEnvironmentVariable(_T("PATH"), NULL, 0);
222
        if(nSize>0){
223
    GetEnvironmentVariable(_T("PATH"),strOldPath.GetBuffer(1+nSize),nSize);
224
    strOldPath.ReleaseBuffer();
225
                // Place the user tools folders at the head or tail of the new path
226
                if(bAtFront){
227
                        strPath.Format(_T("%s;%s"),strFolder.ShortName(),strOldPath);
228
                } else {
229
                        strPath.Format(_T("%s;%s"),strOldPath,strFolder.ShortName());
230
                }
231
        } else {
232
                // unlikely, but ...
233
                strPath=strFolder;
234
        }
235
  return TRUE==::SetEnvironmentVariable(_T("PATH"),strPath);
236
}
237
 
238
 
239
 
240
CString CUtils::GetLastErrorMessageString()
241
{
242
        CString str;
243
        PTCHAR pszMsg;
244
        FormatMessage(
245
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
246
                NULL,
247
                GetLastError(),
248
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
249
                (LPTSTR)&pszMsg,
250
                0,
251
                NULL
252
        );
253
 
254
        // Display the string.
255
        str=pszMsg;
256
  str.TrimRight();
257
        // Free the buffer.
258
        LocalFree(pszMsg);
259
        return str;
260
 
261
}
262
 
263
bool CUtils::Launch(const CFileName &strFileName, const CFileName &strViewer)
264
{
265
        bool rc=false;
266
 
267
        if(!strViewer.IsEmpty())//use custom editor
268
        {
269
                CString strCmdline(strViewer);
270
 
271
                PTCHAR pszCmdLine=strCmdline.GetBuffer(strCmdline.GetLength());
272
                GetShortPathName(pszCmdLine,pszCmdLine,strCmdline.GetLength());
273
                strCmdline.ReleaseBuffer();
274
 
275
                strCmdline+=_TCHAR(' ');
276
                strCmdline+=strFileName;
277
                PROCESS_INFORMATION pi;
278
                STARTUPINFO si;
279
 
280
                si.cb = sizeof(STARTUPINFO);
281
                si.lpReserved = NULL;
282
                si.lpReserved2 = NULL;
283
                si.cbReserved2 = 0;
284
                si.lpDesktop = NULL;
285
                si.dwFlags = 0;
286
                si.lpTitle=NULL;
287
 
288
                if(CreateProcess(
289
                        NULL, // app name
290
                        //strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
291
                        strCmdline.GetBuffer(strCmdline.GetLength()),    // command line
292
                        NULL, // process security
293
                        NULL, // thread security
294
                        TRUE, // inherit handles
295
                        0,
296
                        NULL, // environment
297
                        NULL, // current dir
298
                        &si, // startup info
299
                        &pi)){
300
            CloseHandle(pi.hProcess);
301
            CloseHandle(pi.hThread);
302
                        rc=true;
303
                } else {
304
                        MessageBoxF(_T("Failed to invoke %s.\n"),strCmdline);
305
                }
306
                strCmdline.ReleaseBuffer();
307
        } else {// Use association
308
                TCHAR szExe[MAX_PATH];
309
                HINSTANCE h=FindExecutable(strFileName,_T("."),szExe);
310
                if(int(h)<=32){
311
                        CString str;
312
                        switch(int(h)){
313
                                case 0:  str=_T("The system is out of memory or resources.");break;
314
                                case 31: str=_T("There is no association for the specified file type.");break;
315
                                case ERROR_FILE_NOT_FOUND: str=_T("The specified file was not found.");break;
316
                                case ERROR_PATH_NOT_FOUND: str=_T("The specified path was not found.");break;
317
                                case ERROR_BAD_FORMAT:     str=_T("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image).");break;
318
                                default: break;
319
                        }
320
                        MessageBoxF(_T("Failed to open document %s.\r\n%s"),strFileName,str);
321
                } else {
322
 
323
                        SHELLEXECUTEINFO sei = {sizeof(sei), 0, AfxGetMainWnd()->GetSafeHwnd(), _T("open"),
324
                                        strFileName, NULL, NULL, SW_SHOWNORMAL, AfxGetInstanceHandle( )};
325
 
326
                        sei.hInstApp=0;
327
                        HINSTANCE hInst=ShellExecute(AfxGetMainWnd()->GetSafeHwnd(),_T("open"), strFileName, NULL, _T("."), 0)/*ShellExecuteEx(&sei)*/;
328
                        if(int(hInst)<=32/*sei.hInstApp==0*/)
329
                        {
330
                                CString str;
331
                                switch(int(hInst))
332
                                {
333
                                        case 0 : str=_T("The operating system is out of memory or resources. ");break;
334
                                        case ERROR_FILE_NOT_FOUND : str=_T("The specified file was not found. ");break;
335
                                        case ERROR_PATH_NOT_FOUND : str=_T("The specified path was not found. ");break;
336
                                        case ERROR_BAD_FORMAT : str=_T("The .EXE file is invalid (non-Win32 .EXE or error in .EXE image). ");break;
337
                                        case SE_ERR_ACCESSDENIED : str=_T("The operating system denied access to the specified file. ");break;
338
                                        case SE_ERR_ASSOCINCOMPLETE : str=_T("The filename association is incomplete or invalid. ");break;
339
                                        case SE_ERR_DDEBUSY : str=_T("The DDE transaction could not be completed because other DDE transactions were being processed. ");break;
340
                                        case SE_ERR_DDEFAIL : str=_T("The DDE transaction failed. ");break;
341
                                        case SE_ERR_DDETIMEOUT : str=_T("The DDE transaction could not be completed because the request timed out. ");break;
342
                                        case SE_ERR_DLLNOTFOUND : str=_T("The specified dynamic-link library was not found. ");break;
343
                                        //case SE_ERR_FNF : str=_T("The specified file was not found. ");break;
344
                                        case SE_ERR_NOASSOC : str=_T("There is no application associated with the given filename extension. ");break;
345
                                        case SE_ERR_OOM : str=_T("There was not enough memory to complete the operation. ");break;
346
                                        //case SE_ERR_PNF : str=_T("The specified path was not found. ");break;
347
                                        case SE_ERR_SHARE : str=_T("A sharing violation occurred. ");break;
348
                                        default: str=_T("An unexpected error occurred");break;
349
                                }
350
                                MessageBoxF(_T("Failed to open document %s using %s.\r\n%s"),strFileName,szExe,str);
351
                        } else {
352
                                rc=true;
353
                        }
354
                }
355
        }
356
        return rc;
357
}
358
 
359
void CUtils::UnicodeToCStr(LPCTSTR str,char *&psz)
360
{
361
    int nLength=1+_tcslen(str);
362
    psz=new char[nLength];
363
    #ifdef _UNICODE
364
    WideCharToMultiByte(CP_ACP, 0, str, -1, psz, nLength, NULL, NULL);
365
    #else
366
    strcpy(psz,str);
367
    #endif
368
}
369
 
370
std::string CUtils::UnicodeToStdStr(LPCTSTR str)
371
{
372
    std::string stdstr;
373
    char *psz;
374
    UnicodeToCStr(str,psz);
375
    stdstr=std::string(psz);
376
    delete psz;
377
    return stdstr;
378
}
379
 
380
// CUtils::StripExtraWhitespace() returns a modified version of
381
// a string in which each sequence of whitespace characters is
382
// replaced by a single space
383
 
384
CString CUtils::StripExtraWhitespace (const CString & strInput)
385
{
386
  CString strOutput;
387
  LPTSTR o=strOutput.GetBuffer(1+strInput.GetLength());
388
  for(LPCTSTR c=strInput;*c;c++){
389
    if(_istspace(*c)){
390
      *o++=_TCHAR(' ');
391
      if (_istspace(c[1])){
392
        for(c=c+2;_istspace(*c);c++);
393
        c--;
394
      }
395
    } else {
396
      *o++=*c;
397
    }
398
  }
399
  *o=0;
400
  strOutput.ReleaseBuffer();
401
  strOutput.TrimLeft();
402
  strOutput.TrimRight();
403
  return strOutput;
404
}
405
 
406
CFileName CUtils::WPath(const std::string &str)
407
{
408
  // Convert a path as read from cdl into host format
409
  // Change / to \ throughout
410
  CFileName
411
    strPath(str.c_str());
412
  strPath.Replace (_TCHAR('/'), _TCHAR('\\'));
413
  return strPath;
414
}
415
 
416
// Copy file helper function.
417
// This makes sure the destination file is only touched as necessary.
418
// It is written using Posix calls lest it should be more broadly applicable.
419
 
420
bool CUtils::CopyFile(LPCTSTR pszSource,LPCTSTR pszDest)
421
{
422
  // Compare the files.  First set rc to the result of the comparison (true if the same)
423
  bool rc=false;
424
 
425
  struct _stat s1,s2;
426
  if(-1!=_tstat(pszSource,&s1) && -1!=_tstat(pszDest,&s2) && s1.st_size==s2.st_size){
427
    // Files both exist and are of equal size
428
    FILE *f1=_tfopen(pszSource,_T("rb"));
429
    if(f1){
430
      FILE *f2=_tfopen(pszDest,_T("rb"));
431
      if(f2){
432
        int nSize1,nSize2;
433
        rc=true;
434
        do{
435
          char buf1[4096],buf2[4096];
436
          nSize1=fread(buf1,1,sizeof buf1,f1);
437
          nSize2=fread(buf2,1,sizeof buf2,f2);
438
          if(nSize1!=nSize2 || 0!=memcmp(buf1,buf2,nSize1)){
439
            rc=false;
440
            break;
441
          }
442
        } while (nSize1>0);
443
        fclose(f2);
444
      }
445
      fclose(f1);
446
    }
447
  }
448
 
449
  if(rc){
450
    // Files are identical
451
    TRACE(_T("Copy not necessary: '%s' to '%s'\n"),pszSource,pszDest);
452
  } else {
453
    rc=TRUE==::CopyFile(pszSource,pszDest,FALSE);
454
    if(rc){
455
      TRACE(_T("Copied '%s' to '%s'\n"),pszSource,pszDest);
456
    } else {
457
      MessageBoxF(_T("Failed to copy '%s' to '%s' - %s"),pszSource,pszDest,GetLastErrorMessageString());
458
    }
459
  }
460
 
461
  return rc;
462
}

powered by: WebSVN 2.1.0

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