示例#1
0
void XmlConfig::SetPath(const wxString& path)
{

    wxArrayString aParts;

    if (!path.empty() )
    {
        if ( path[0] == wxCONFIG_PATH_SEPARATOR )
        {
            // Absolute path
            wxSplitPath(aParts, path);
        }
        else
        {
            // Relative path, combine with current one
            wxString strFullPath = m_path;
            strFullPath << wxCONFIG_PATH_SEPARATOR << path;
            wxSplitPath(aParts, strFullPath);
        }
    }

    // recombine path parts in one variable
    m_path.Empty();
    for (unsigned int n = 0; n < aParts.Count(); n++ ) {
        m_path << wxCONFIG_PATH_SEPARATOR << aParts[n];
    }

    m_pathNode = GetGroupNode(aParts);

}
示例#2
0
文件: filedlgwce.cpp 项目: EdgarTx/wx
void wxFileDialog::SetPath(const wxString& path)
{
    wxString ext;
    wxSplitPath(path, &m_dir, &m_fileName, &ext);
    if ( !ext.empty() )
        m_fileName << _T('.') << ext;
}
示例#3
0
文件: helpctrl.cpp 项目: Ailick/rpcs3
bool wxHtmlHelpController::Initialize(const wxString& file)
{
    wxString dir, filename, ext;
    wxSplitPath(file, & dir, & filename, & ext);

    if (!dir.empty())
        dir = dir + wxFILE_SEP_PATH;

    // Try to find a suitable file
    wxString actualFilename = dir + filename + wxString(wxT(".zip"));
    if (!wxFileExists(actualFilename))
    {
        actualFilename = dir + filename + wxString(wxT(".htb"));
        if (!wxFileExists(actualFilename))
        {
            actualFilename = dir + filename + wxString(wxT(".hhp"));
            if (!wxFileExists(actualFilename))
            {
#if wxUSE_LIBMSPACK
                actualFilename = dir + filename + wxString(wxT(".chm"));
                if (!wxFileExists(actualFilename))
#endif
                    return false;
            }
        }
    }
    return AddBook(wxFileName(actualFilename));
}
示例#4
0
void wxIniConfig::SetPath(const wxString& strPath)
{
    wxArrayString aParts;

    if ( strPath.empty() )
    {
        // nothing
    }
    else if ( strPath[(size_t) 0] == wxCONFIG_PATH_SEPARATOR )
    {
        // absolute path
        wxSplitPath(aParts, strPath);
    }
    else
    {
        // relative path, combine with current one
        wxString strFullPath = GetPath();
        strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
        wxSplitPath(aParts, strFullPath);
    }

    size_t nPartsCount = aParts.Count();
    m_strPath.Empty();
    if ( nPartsCount == 0 )
    {
        // go to the root
        m_strGroup = (wxChar*)PATH_SEP_REPLACE;
    }
    else
    {
        // translate
        m_strGroup = aParts[(size_t) 0];
        for ( size_t nPart = 1; nPart < nPartsCount; nPart++ )
        {
            if ( nPart > 1 )
                m_strPath << PATH_SEP_REPLACE;
            m_strPath << aParts[nPart];
        }
    }

    // other functions assume that all this is true, i.e. there are no trailing
    // underscores at the end except if the group is the root one
    wxASSERT( (m_strPath.empty() || m_strPath.Last() != PATH_SEP_REPLACE) &&
              (m_strGroup == wxString((wxChar)PATH_SEP_REPLACE) ||
               m_strGroup.Last() != PATH_SEP_REPLACE) );
}
示例#5
0
void SetUpWorkingDirectories(const char* argv0)
{
    // set up working directories
    workingDir = wxGetCwd().c_str();
#ifdef __WXGTK__
    if (getenv("CN3D_HOME") != NULL)
        programDir = getenv("CN3D_HOME");
    else
#endif
    if (wxIsAbsolutePath(argv0))
        programDir = wxPathOnly(argv0).c_str();
    else if (wxPathOnly(argv0) == "")
        programDir = workingDir;
    else
        programDir = workingDir + wxFILE_SEP_PATH + wxPathOnly(argv0).c_str();
    workingDir = workingDir + wxFILE_SEP_PATH;
    programDir = programDir + wxFILE_SEP_PATH;

    // find or create preferences folder
    wxString localDir;
    wxSplitPath((wxFileConfig::GetLocalFileName("unused")).c_str(), &localDir, NULL, NULL);
    wxString prefsDirLocal = localDir + wxFILE_SEP_PATH + "Cn3D_User";
    wxString prefsDirProg = wxString(programDir.c_str()) + wxFILE_SEP_PATH + "Cn3D_User";
    if (wxDirExists(prefsDirLocal))
        prefsDir = prefsDirLocal.c_str();
    else if (wxDirExists(prefsDirProg))
        prefsDir = prefsDirProg.c_str();
    else {
        // try to create the folder
        if (wxMkdir(prefsDirLocal) && wxDirExists(prefsDirLocal))
            prefsDir = prefsDirLocal.c_str();
        else if (wxMkdir(prefsDirProg) && wxDirExists(prefsDirProg))
            prefsDir = prefsDirProg.c_str();
    }
    if (prefsDir.size() == 0)
        WARNINGMSG("Can't create Cn3D_User folder at either:"
            << "\n    " << prefsDirLocal
            << "\nor  " << prefsDirProg);
    else
        prefsDir += wxFILE_SEP_PATH;

    // set data dir, and register the path in C toolkit registry (mainly for BLAST code)
#ifdef __WXMAC__
    dataDir = programDir + "../Resources/data/";
#else
    dataDir = programDir + "data" + wxFILE_SEP_PATH;
#endif

    TRACEMSG("working dir: " << workingDir.c_str());
    TRACEMSG("program dir: " << programDir.c_str());
    TRACEMSG("data dir: " << dataDir.c_str());
    TRACEMSG("prefs dir: " << prefsDir.c_str());
}
示例#6
0
void WinEDA_PlotPSFrame::CreatePSFile(int AllPages, int pagesize)
/*************************************************************/
{
wxString PlotFileName, ShortFileName;
BASE_SCREEN *screen;
Ki_PageDescr * PlotSheet, * RealSheet;
int BBox[4];
wxPoint plot_offset;

	SchematicCleanUp(NULL);
	g_PlotFormat = PLOT_FORMAT_POST;

	screen = ActiveScreen;
	if ( AllPages == TRUE )
	{
		screen = ScreenSch;
	}
	while( screen )
	{
		PlotSheet = screen->m_CurrentSheet;
		RealSheet = &g_Sheet_A4;
		if ( pagesize == PAGE_SIZE_AUTO ) RealSheet = PlotSheet;
		else if ( pagesize == PAGE_SIZE_A )	RealSheet = &g_Sheet_A;

		/* Calcul des limites de trace en 1/1000 pouce */
		BBox[0] = BBox[1] = g_PlotMargin;	// Plot margin in 1/1000 inch
		BBox[2] = RealSheet->m_Size.x - g_PlotMargin;
		BBox[3] = RealSheet->m_Size.y - g_PlotMargin;

		/* Calcul des echelles de conversion */
		g_PlotScaleX = SCALE_PS *
					(float) (BBox[2] - BBox[0]) /
					PlotSheet->m_Size.x;
		g_PlotScaleY = SCALE_PS *
					(float) (BBox[3] - BBox[1]) /
					PlotSheet->m_Size.y;

		plot_offset.x = 0;
		plot_offset.y = PlotSheet->m_Size.y;

		wxSplitPath(screen->m_FileName.GetData(), (wxString*) NULL,
				&ShortFileName, (wxString*) NULL);
		wxString dirbuf = wxGetCwd() + STRING_DIR_SEP;
		if( ! ShortFileName.IsEmpty() )
			PlotFileName = MakeFileName(dirbuf, ShortFileName, wxT(".ps"));
		else PlotFileName = MakeFileName(dirbuf, g_DefaultSchematicFileName, wxT(".ps"));

		PlotOneSheetPS(PlotFileName,screen, RealSheet, BBox, plot_offset);
		screen = (BASE_SCREEN*)screen->Pnext;
		if (AllPages == FALSE ) screen = NULL;
	}
}
示例#7
0
void WinEDA_PlotHPGLFrame::Plot_Schematic_HPGL(int Select_PlotAll, int HPGL_SheetSize)
/***********************************************************************************/
{
wxString PlotFileName, ShortFileName;
BASE_SCREEN *screen;
Ki_PageDescr * PlotSheet;
wxSize SheetSize;
wxPoint SheetOffset, PlotOffset;
int margin;

	SchematicCleanUp(NULL);
	g_PlotFormat = PLOT_FORMAT_HPGL;

	screen = ActiveScreen;
	if ( Select_PlotAll == TRUE )
	{
		screen = ScreenSch;
	}
	while( screen )
	{
		ReturnSheetDims(screen, SheetSize, SheetOffset);
		/* Calcul des echelles de conversion */
		g_PlotScaleX = Scale_X * SCALE_HPGL ;
		g_PlotScaleY = Scale_Y * SCALE_HPGL ;

		margin = 400;	// Margin in mils
		PlotSheet = screen->m_CurrentSheet;
		g_PlotScaleX = g_PlotScaleX * (SheetSize.x - 2 * margin)/ PlotSheet->m_Size.x;
		g_PlotScaleY = g_PlotScaleY * (SheetSize.y - 2 * margin) / PlotSheet->m_Size.y;

		/* calcul des offsets */
		PlotOffset.x = - (int)(SheetOffset.x * SCALE_HPGL);
		PlotOffset.y = (int)( (SheetOffset.y + SheetSize.y) * SCALE_HPGL);
		PlotOffset.x -= (int)(margin * SCALE_HPGL);
		PlotOffset.y += (int)(margin * SCALE_HPGL);

		wxSplitPath(screen->m_FileName.GetData(), (wxString*) NULL,
				&ShortFileName, (wxString*) NULL);
		wxString dirbuf = wxGetCwd() + STRING_DIR_SEP;
		if( ! ShortFileName.IsEmpty() )
			PlotFileName = MakeFileName(dirbuf, ShortFileName, wxT(".plt"));
		else PlotFileName = MakeFileName(dirbuf, g_DefaultSchematicFileName, wxT(".plt"));

		InitPlotParametresHPGL(PlotOffset, g_PlotScaleX, g_PlotScaleY);
		Plot_1_Page_HPGL(PlotFileName,screen);
		screen = (BASE_SCREEN*)screen->Pnext;
		if ( Select_PlotAll == FALSE ) screen = NULL;
	}

	m_MsgBox->AppendText(_("** Plot End **\n"));
}
示例#8
0
// Append extension if necessary.
wxString wxCHMHelpController::GetValidFilename(const wxString& file) const
{
    wxString path, name, ext;
    wxSplitPath(file, & path, & name, & ext);

    wxString fullName;
    if (path.IsEmpty())
        fullName = name + wxT(".chm");
    else if (path.Last() == wxT('\\'))
        fullName = path + name + wxT(".chm");
    else
        fullName = path + wxT("\\") + name + wxT(".chm");
    return fullName;
}
bool palm_installer_base::install_files_by_directory( const wxString &output_directory,
                                                      wxArrayString &install_fullnames )
{
    wxString    output_fullname;
    wxString    install_fullname;
    wxString    install_filename;
    wxString    install_basename;
    wxString    install_extension;
    bool        copy_successful     = FALSE;

    // Abort if output directory is empty, or doesn't exist
    if ( output_directory == wxT( "" ) || ! wxDirExists( output_directory ) ) 
    {
        return FALSE;
    }

    // Remove any trailing dir separators from the output directory string
    // (which can happen for example in 'C:\' returned from wxDirDialog.
    wxString stripped_output_directory = utils_string::remove_trailing_dir_separator( output_directory );

    // Loop through all the input_files copying them over to the directory
    for ( int n=0; n < (int)install_fullnames.GetCount(); n++ ) 
    {
        install_fullname = install_fullnames.Item( n );

        // Only proceed if this install_fullname exists.
        if ( wxFileExists( install_fullname ) )
        {
            // Extract the basename and extension from input_fullname, so 
            // can use it for the target files to copy.
            wxSplitPath( install_fullname.c_str(), NULL, &install_basename,
                         &install_extension );
            install_filename = install_basename + wxT( "." ) + install_extension;                
            output_fullname = stripped_output_directory + wxT( "/" ) + install_filename;
    
            // TRUE as 3rd parameter, since certainly want to overwrite it.
            copy_successful = wxCopyFile( install_fullname, output_fullname, TRUE );

            wxLogDebug( wxT( "Success=%ld in attempt to copy %s to %s" ), (long)copy_successful,
                        install_fullname.c_str(), output_fullname.c_str() );
        } 
        else
        {
            wxLogDebug( wxT( "Error: Can't find file %s to copy" ), install_fullname.c_str() );
        }
    }

    return copy_successful;
}
示例#10
0
void wxFileConfig::SetPath(const wxString& strPath)
{
  wxArrayString aParts;

  if ( strPath.IsEmpty() ) {
    SetRootPath();
    return;
  }

  if ( strPath[0] == wxCONFIG_PATH_SEPARATOR ) {
    // absolute path
    wxSplitPath(aParts, strPath);
  }
  else {
    // relative path, combine with current one
    wxString strFullPath = m_strPath;
    strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
    wxSplitPath(aParts, strFullPath);
  }

  // change current group
  size_t n;
  m_pCurrentGroup = m_pRootGroup;
  for ( n = 0; n < aParts.Count(); n++ ) {
    ConfigGroup *pNextGroup = m_pCurrentGroup->FindSubgroup(aParts[n]);
    if ( pNextGroup == NULL )
      pNextGroup = m_pCurrentGroup->AddSubgroup(aParts[n]);
    m_pCurrentGroup = pNextGroup;
  }

  // recombine path parts in one variable
  m_strPath.Empty();
  for ( n = 0; n < aParts.Count(); n++ ) {
    m_strPath << wxCONFIG_PATH_SEPARATOR << aParts[n];
  }
}
示例#11
0
//仅搜索扩展名
bool ThreadWork::fitExtendName( wxString &path )
{
	wxString extName;	wxString ret;	wxString par = parItems[6];
	wxSplitPath( path, NULL, NULL, &extName );

	wxRegEx re( "\\w\\S*", wxRE_ADVANCED  );
	while( re.Matches( par ) )
	{
		ret = re.GetMatch( par );
		if( ret == extName )
			return true;
		par.Replace( ret, _T(""), false );
	}

	return false;
}
示例#12
0
wxArrayString XmlResApp::PrepareTempFiles()
{
    wxArrayString flist;

    for (size_t i = 0; i < parFiles.Count(); i++)
    {
        if (flagVerbose)
            wxPrintf(_T("processing ") + parFiles[i] +  _T("...\n"));

        wxXmlDocument doc;

        if (!doc.Load(parFiles[i]))
        {
            wxLogError(_T("Error parsing file ") + parFiles[i]);
            retCode = 1;
            continue;
        }

        wxString name, ext, path;
        wxSplitPath(parFiles[i], &path, &name, &ext);

        FindFilesInXML(doc.GetRoot(), flist, path);
        if (flagH)
        {
            wxXmlNode* node = (doc.GetRoot())->GetChildren();
                wxString classValue,nameValue;
                while(node){
                    if(node->GetName() == _T("object")
                     && node->GetPropVal(_T("class"),&classValue)
                     && node->GetPropVal(_T("name"),&nameValue)){

                      aXRCWndClassData.Add(
                        XRCWndClassData(nameValue,classValue,node)
                      );
                    }
                    node = node -> GetNext();
            }
        }
        wxString internalName = GetInternalFileName(parFiles[i], flist);

        doc.Save(parOutputPath + wxFILE_SEP_PATH + internalName);
        flist.Add(internalName);
    }

    return flist;
}
示例#13
0
文件: helpwce.cpp 项目: Duion/Torsion
// Append extension if necessary.
wxString wxWinceHelpController::GetValidFilename(const wxString& file) const
{
    wxString path, name, ext;
    wxSplitPath(file, & path, & name, & ext);

    wxString fullName;
    if (path.IsEmpty())
        fullName = name + wxT(".htm");
    else if (path.Last() == wxT('\\'))
        fullName = path + name + wxT(".htm");
    else
        fullName = path + wxT("\\") + name + wxT(".htm");

    if (!wxFileExists(fullName))
        fullName = wxT("\\Windows\\") + name + wxT(".htm");

    return fullName;
}
示例#14
0
/** Does given file contain catalogs in given language?
    Handles these cases:
      - foo/bar/lang.mo
      - foo/lang/bar.mo
      - foo/lang/LC_MESSAGES/bar.mo
    Futhermore, if \a lang is 2-letter code (e.g. "cs"), handles these:
      - foo/bar/lang_??.mo
      - foo/lang_??/bar.mo
      - foo/lang_??/LC_MESSAGES/bar.mo
    and if \a lang is five-letter code (e.g. "cs_CZ"), tries to match its
    first two letters (i.e. country-neutral variant of the language).
 */
static inline bool IsForLang(const wxString& filename, const wxString& lang,
                             bool variants = true)
{
#ifdef __WINDOWS__
    #define LC_MESSAGES_STR "/lc_messages"
#else
    #define LC_MESSAGES_STR "/LC_MESSAGES"
#endif
    wxString base, dir;
    wxSplitPath(filename, &dir, &base, NULL);
    dir.Replace(wxString(wxFILE_SEP_PATH), "/");
    return base.Matches(lang) ||
           dir.Matches("*/" + lang) ||
           dir.Matches("*/" + lang + LC_MESSAGES_STR) ||
           (variants && lang.Len() == 5 && lang[2] == _T('_') && 
                IsForLang(filename, lang.Mid(0, 2), false)) ||
           (variants && lang.Len() == 2 && 
                IsForLang(filename, lang + "_??", false));
    #undef LC_MESSAGES_STR
}
示例#15
0
void wxGenericFileDialog::SetPath( const wxString& path )
{
    // not only set the full path but also update filename and dir
    m_path = path;

#ifdef __WXWINCE__
    if (m_path.empty())
        m_path = wxFILE_SEP_PATH;
#endif

    if ( !path.empty() )
    {
        wxString ext;
        wxSplitPath(path, &m_dir, &m_fileName, &ext);
        if (!ext.empty())
        {
            m_fileName += wxT(".");
            m_fileName += ext;
        }
    }
}
示例#16
0
// Returns the image type, or -1, determined from the extension.
wxBitmapType wxDetermineImageType(const wxString& filename)
{
    wxString path, name, ext;

    wxSplitPath(filename, & path, & name, & ext);

    ext.MakeLower();
    if (ext == _T("jpg") || ext == _T("jpeg"))
        return wxBITMAP_TYPE_JPEG;
    if (ext == _T("gif"))
        return wxBITMAP_TYPE_GIF;
    if (ext == _T("bmp"))
        return wxBITMAP_TYPE_BMP;
    if (ext == _T("png"))
        return wxBITMAP_TYPE_PNG;
    if (ext == _T("pcx"))
        return wxBITMAP_TYPE_PCX;
    if (ext == _T("tif") || ext == _T("tiff"))
        return wxBITMAP_TYPE_TIF;

    return wxBITMAP_TYPE_INVALID;
}
示例#17
0
// Returns the image type, or -1, determined from the extension.
int wxDetermineImageType(const wxString& filename)
{
    wxString path, name, ext;

    wxSplitPath(filename, & path, & name, & ext);

    ext.MakeLower();
    if (ext == wxT("jpg") || ext == wxT("jpeg"))
        return wxBITMAP_TYPE_JPEG;
    else if (ext == wxT("gif"))
        return wxBITMAP_TYPE_GIF;
    else if (ext == wxT("bmp"))
        return wxBITMAP_TYPE_BMP;
    else if (ext == wxT("png"))
        return wxBITMAP_TYPE_PNG;
    else if (ext == wxT("pcx"))
        return wxBITMAP_TYPE_PCX;
    else if (ext == wxT("tif") || ext == wxT("tiff"))
        return wxBITMAP_TYPE_TIF;
    else
        return -1;
}
示例#18
0
void wxGenericFileDialog::HandleAction( const wxString &fn )
{
    if (ignoreChanges)
        return;

    wxString filename( fn );
    wxString dir = m_list->GetDir();
    if (filename.empty()) return;
    if (filename == wxT(".")) return;

    // "some/place/" means they want to chdir not try to load "place"
    bool want_dir = filename.Last() == wxFILE_SEP_PATH;
    if (want_dir)
        filename = filename.RemoveLast();

    if (filename == wxT(".."))
    {
        ignoreChanges = true;
        m_list->GoToParentDir();
        m_list->SetFocus();
        UpdateControls();
        ignoreChanges = false;
        return;
    }

#ifdef __UNIX__
    if (filename == wxT("~"))
    {
        ignoreChanges = true;
        m_list->GoToHomeDir();
        m_list->SetFocus();
        UpdateControls();
        ignoreChanges = false;
        return;
    }

    if (filename.BeforeFirst(wxT('/')) == wxT("~"))
    {
        filename = wxString(wxGetUserHome()) + filename.Remove(0, 1);
    }
#endif // __UNIX__

    if (!(m_dialogStyle & wxSAVE))
    {
        if ((filename.Find(wxT('*')) != wxNOT_FOUND) ||
                (filename.Find(wxT('?')) != wxNOT_FOUND))
        {
            if (filename.Find(wxFILE_SEP_PATH) != wxNOT_FOUND)
            {
                wxMessageBox(_("Illegal file specification."), _("Error"), wxOK | wxICON_ERROR );
                return;
            }
            m_list->SetWild( filename );
            return;
        }
    }

    if (!IsTopMostDir(dir))
        dir += wxFILE_SEP_PATH;
    if (!wxIsAbsolutePath(filename))
    {
        dir += filename;
        filename = dir;
    }

    if (wxDirExists(filename))
    {
        ignoreChanges = true;
        m_list->GoToDir( filename );
        UpdateControls();
        ignoreChanges = false;
        return;
    }

    // they really wanted a dir, but it doesn't exist
    if (want_dir)
    {
        wxMessageBox(_("Directory doesn't exist."), _("Error"),
                     wxOK | wxICON_ERROR );
        return;
    }

    // append the default extension to the filename if it doesn't have any
    //
    // VZ: the logic of testing for !wxFileExists() only for the open file
    //     dialog is not entirely clear to me, why don't we allow saving to a
    //     file without extension as well?
    if ( !(m_dialogStyle & wxOPEN) || !wxFileExists(filename) )
    {
        filename = AppendExtension(filename, m_filterExtension);
    }

    // check that the file [doesn't] exist if necessary
    if ( (m_dialogStyle & wxSAVE) &&
            (m_dialogStyle & wxOVERWRITE_PROMPT) &&
            wxFileExists( filename ) )
    {
        wxString msg;
        msg.Printf( _("File '%s' already exists, do you really want to overwrite it?"), filename.c_str() );

        if (wxMessageBox(msg, _("Confirm"), wxYES_NO) != wxYES)
            return;
    }
    else if ( (m_dialogStyle & wxOPEN) &&
              (m_dialogStyle & wxFILE_MUST_EXIST) &&
              !wxFileExists(filename) )
    {
        wxMessageBox(_("Please choose an existing file."), _("Error"),
                     wxOK | wxICON_ERROR );
    }

    SetPath( filename );

    // change to the directory where the user went if asked
    if ( m_dialogStyle & wxCHANGE_DIR )
    {
        wxString cwd;
        wxSplitPath(filename, &cwd, NULL, NULL);

        if ( cwd != wxGetCwd() )
        {
            wxSetWorkingDirectory(cwd);
        }
    }

    wxCommandEvent event;
    wxDialog::OnOK(event);
}
示例#19
0
bool MFolderFromProfile::Create(const String& fullname)
{
   // update the count of children in the immediate parent of the folder we're
   // going to create

   // split path into '/' separated components
   wxArrayString components;
   wxSplitPath(components, fullname);

   bool updatedCount = false;

   String path, component;

   Profile *profile = Profile::CreateFolderProfile(wxEmptyString);

   size_t n,
          count = components.GetCount();
   for ( n = 0; n < count; n++ )
   {
      CHECK( profile, false, _T("failed to create profile?") );

      component = components[n];

      if ( !updatedCount )
      {
         if ( profile->readEntryFromHere(component + _T('/') + MP_FOLDER_TYPE,
                                         MF_ILLEGAL) == MF_ILLEGAL )
         {
            MFolderFromProfile *folder = (MFolderFromProfile *)MFolder::Get(path);
            if ( !folder )
            {
               FAIL_MSG( _T("this folder must already exist!") );
            }
            else
            {
               // we have to invalidate it - unfortunately we can't just
               // increase it because we may have a situation like this:
               //
               //    1. Create("a/b/c")
               //    2. Create("a/b")
               //    3. Create("a")
               //
               // and then, assuming 'a' hadn't existed before, the children
               // count of the root folder would be incremented thrice even
               // though only one new children was created
               folder->m_nChildren = INVALID_CHILDREN_COUNT;

               folder->DecRef();
            }

            // this is the the last existing folder for which we have anything to
            // update
            updatedCount = true;
         }
      }

      // go down
      if ( !path.empty() )
         path += _T('/');
      path += components[n];

      profile->DecRef();
      profile = Profile::CreateFolderProfile(path);
   }

   // we need to write something to this group to really create it
   profile->writeEntry(MP_FOLDER_TYPE, MF_ILLEGAL);

   profile->DecRef();

   return true;
}
示例#20
0
//----------------------------------------------------------------------------
void medLogicWithManagers::OnEvent(mafEventBase *maf_event)
//----------------------------------------------------------------------------
{
	if (mafEvent *e = mafEvent::SafeDownCast(maf_event))
	{
		switch(e->GetId())
		{
		  case ABOUT_APPLICATION:
			{
        // trap the ABOUT_APPLICATION event and shows the about window with the application infos
				wxString message = m_AppTitle.GetCStr();
				message += _(" Application ");
				message += m_Revision;
				wxMessageBox(message, "About Application");
				mafLogMessage(wxString::Format("%s",m_Revision.GetCStr()));
			}
		 break;
		 case ID_GET_FILENAME:
			  {
				  e->SetString(&(m_VMEManager->GetFileName()));
			  }
			  break;
		 case MENU_FILE_SNAPSHOT:
			  {
				  mafString msfFilename = m_VMEManager->GetFileName();
				  if (msfFilename.IsEmpty())
				  {
					  mafString dirName = mafGetApplicationDirectory().c_str();
					  dirName << "\\data\\msf\\";

					  m_VMEManager->SetDirName(dirName);
					  this->OnFileSaveAs();
					  this->OnEvent((mafEventBase*)&mafEvent(this,CAMERA_UPDATE));
					  msfFilename = m_VMEManager->GetFileName();
				  }

				  wxString path, name, ext;
				  wxSplitPath(msfFilename.GetCStr(),&path,&name,&ext);
				  wxString imagesDirectoryName = path;
				  imagesDirectoryName += "/images";
				  if (!::wxDirExists(imagesDirectoryName))
				  {
					  ::wxMkdir(imagesDirectoryName);
				  }

				  wxDir imagesDirectory(imagesDirectoryName);
				  wxString filename;
				  int i = 0;
				  bool cont = imagesDirectory.GetFirst(&filename);
				  while ( cont )
				  {
					  i++;
					  cont = imagesDirectory.GetNext(&filename);
				  }

				  if (e->GetString() && !(e->GetString()->IsEmpty()))
				  {
					  mafString *imageFileName = new mafString();
					  imageFileName->Append(imagesDirectoryName.c_str());
					  imageFileName->Append("/");
					  imageFileName->Append(e->GetString()->GetCStr());
					  imageFileName->Append(wxString::Format("_%d",i));
					  imageFileName->Append(".png");

					  /*mafRWIBase::SafeDownCast(e->GetVtkObj())->SaveImage(imageFileName);*/
					  e->SetString(imageFileName);

					  wxString path,name,ext;
					  wxSplitPath(imageFileName->GetCStr(),&path,&name,&ext);
					  wxString oldWD = wxGetWorkingDirectory();
					  wxSetWorkingDirectory(path);
					  wxString command = "START  ";
					  command = command + name+"."+ext;
					  wxExecute( command );
					  wxSetWorkingDirectory(oldWD);


				  }
				  else
				  {
					  wxString imageFileName = "";
					  mafViewCompound *v = mafViewCompound::SafeDownCast(m_ViewManager->GetSelectedView());
					  if (v)
					  {
						  imageFileName = imagesDirectoryName;
						  imageFileName << "/";
						  wxString tmpImageFile;
						  tmpImageFile << v->GetLabel();
						  tmpImageFile << i;
						  tmpImageFile << ".png";

						  tmpImageFile.Replace(" ","_");

						  imageFileName << tmpImageFile;

						  v->GetRWI()->SaveAllImages(imageFileName,v, m_ApplicationSettings->GetImageTypeId());

						  wxMessageBox(_("Snapshot saved!"));
					  }
					  else
					  {
						  mafView *v = m_ViewManager->GetSelectedView();

						  imageFileName = imagesDirectoryName;
						  imageFileName << "/";
						  wxString tmpImageFile;
						  tmpImageFile << v->GetLabel();
						  tmpImageFile << i;
						  tmpImageFile << ".png";

						  tmpImageFile.Replace(" ","_");

						  imageFileName << tmpImageFile;

						  if (v)
						  {
							  v->GetRWI()->SaveImage(imageFileName);
							  wxMessageBox(_("Snapshot saved!"));
						  }
					  }

					  wxString path,name,ext;
					  wxSplitPath(imageFileName,&path,&name,&ext);
					  wxString oldWD = wxGetWorkingDirectory();
					  wxSetWorkingDirectory(path);
					  wxString command = "START  ";
					  command = command + name+"."+ext;
					  wxShell( command );
					  wxSetWorkingDirectory(oldWD);
				  }

				  OnEvent(&mafEvent(this,WIZARD_RUN_CONTINUE,true));
			  }
		break;
     case MENU_WIZARD:
      //The event from the application menu
      if(m_WizardManager) 
        m_WizardManager->WizardRun(e->GetArg());
     break;
     case WIZARD_RUN_STARTING:
      {
        //Manage start event from the wizard lock window close button
        //and disabling toolbar
        mafGUIMDIChild *c = (mafGUIMDIChild *)m_Win->GetActiveChild();
        if (c != NULL)
          c->SetAllowCloseWindow(false);
        WizardRunStarting();
      }
     break; 
     case WIZARD_RUN_TERMINATED:
      {
        //Manage end event from the wizard unlock window close button
        //and enabling toolbar
        mafGUIMDIChild *c = (mafGUIMDIChild *)m_Win->GetActiveChild();
        if (c != NULL)
          c->SetAllowCloseWindow(true);
        WizardRunTerminated();
        UpdateFrameTitle();
      }
    break;
	 case WIZARD_RUN_CONTINUE:
	 {
		 if (m_WizardManager && m_WizardRunning)
			 m_WizardManager->WizardContinue(e->GetBool());
	 }
	 break;
    case WIZARD_UPDATE_WINDOW_TITLE:
       {
         UpdateFrameTitle();
       }
    break;
    case WIZARD_REQUIRED_VIEW:
       {
         //The wizard requires a specific view
         //searching on open views or open a new one
         mafView *view;
         const char *viewStr=e->GetString()->GetCStr();
         
         view=m_ViewManager->GetFromList(viewStr);
         if (view)
           m_ViewManager->Activate(view);
         else
           m_ViewManager->ViewCreate(viewStr);
       }
    break;
	case WIZARD_DELETE_VIEW:
		{
			mafView *view;
			const char *viewStr=e->GetString()->GetCStr();

			view=m_ViewManager->GetFromList(viewStr);
			if (view) 
			{
				mafGUIMDIChild *c = (mafGUIMDIChild *)view->GetFrame();
				m_ViewManager->ViewDelete(view);
				if (c != NULL)
					c->Destroy();
			}
		}
	break;
    case WIZARD_RUN_OP:
      {
        //Running an op required from the wizard
        mafString *tmp=e->GetString();
        mafLogMessage("wiz starting :%s",tmp->GetCStr());
        m_CancelledBeforeOpStarting=true;
        UpdateFrameTitle();
        m_OpManager->OpRun(*(e->GetString()));
        //If the op is started the value of m_CancelledBeforeOpStarting 
        //is changed by OP_RUN_STARTING event
        if (m_CancelledBeforeOpStarting)
        {
          m_CancelledBeforeOpStarting=false;
           m_WizardManager->WizardContinue(false);
        }
        
      }
    break;
    case WIZARD_OP_DELETE:
      {
        //Running an op required from the wizard
        m_CancelledBeforeOpStarting=true;
        UpdateFrameTitle();
        m_OpManager->OpRun(OP_DELETE);
        m_WizardManager->WizardContinue(true);
      }
    break;
    case WIZARD_OP_NEW:
      {
        //Running an op required from the wizard
        if(m_VMEManager)
          m_VMEManager->MSFNew();
        m_WizardManager->WizardContinue(true);
      }
    break;
    case WIZARD_PAUSE:
      {
        UpdateFrameTitle();
        m_OpManager->OpRun(e->GetOp());
      }
      break;
    case WIZARD_RELOAD_MSF:
      {
        UpdateFrameTitle();
        wxString file;
        file=m_VMEManager->GetFileName().GetCStr();
        if(file.IsEmpty())
        {
          mafLogMessage ("Reload requested whitout opened MSF");
          //continue wizard with error
          m_WizardManager->WizardContinue(false);
        }
        else
        {
          int opened=m_VMEManager->MSFOpen(file);
          //continue wizard after open operation
          m_WizardManager->WizardContinue(opened!=MAF_ERROR);
        }
      }
      break;
    case OP_RUN_STARTING:
      {
        mafLogMessage("run starting");
        m_CancelledBeforeOpStarting=false;
        mafLogicWithManagers::OnEvent(maf_event);
      }
    break;
    case OP_RUN_TERMINATED:
      {
        //if the operation was started from the wizard we continue the wizard execution
        if (m_WizardManager && m_WizardRunning)
        {
          m_WizardManager->WizardContinue(e->GetArg());
        }
        //else we manage the operation end by unlock the close button and so on
        else
        {
          mafGUIMDIChild *c = (mafGUIMDIChild *)m_Win->GetActiveChild();
          if (c != NULL)
            c->SetAllowCloseWindow(true);
          OpRunTerminated();
        }
      }
      break; 
	case MENU_VIEW_TOOLBAR:
		m_Win->ShowDockPane("wizardgauge",!m_Win->DockPaneIsShown("wizardgauge") );
		m_Win->ShowDockPane("tmpwithtest",!m_Win->DockPaneIsShown("tmpwithtest") );
		m_Win->ShowDockPane("separator",!m_Win->DockPaneIsShown("separator") );
		mafLogicWithManagers::OnEvent(maf_event);
		break;
    case PROGRESSBAR_SHOW:
     {
       if (e->GetSender()==m_WizardManager)
       {
         m_WizardLabel->Enable();
         m_WizardGauge->Enable();
       }
       else
         mafLogicWithManagers::OnEvent(maf_event);
     }
    break;
    case PROGRESSBAR_HIDE:
      {
        if (e->GetSender()==m_WizardManager)
        {
          m_WizardGauge->SetValue(0);
          m_WizardGauge->Enable(false);
          m_WizardLabel->Enable(false);
        }
        else
          mafLogicWithManagers::OnEvent(maf_event);
      }
    break;
    case PROGRESSBAR_SET_VALUE:
      {
        if (e->GetSender()==m_WizardManager)
          m_WizardGauge->SetValue(e->GetArg());
        else
          mafLogicWithManagers::OnEvent(maf_event);
      }
    break;
		default:
      //Call parent event manager
			mafLogicWithManagers::OnEvent(maf_event);
			break; 
		} // end switch case
	} // end if SafeDowncast
}
bool palm_installer::install_files_by_handheld_dest( handheld_dest_type& handheld_dest,
        wxArrayString& install_fullnames )
{
    wxString    destination_fullname;
    wxString    destination_path;
    wxString    destination_rootpath;
    wxString    destination_basename;
    wxString    destination_extension;
    int         user_index;
    wxString    install_fullname;
    bool        install_fullname_exists = false;
    bool        successful              = false;

    // This is a dummy to induce a translatable string, when we want the original to stay as untranslated.
    wxString 	dummy1 = _( "SecureDigital (SD) Card" );

    wxLogDebug( wxT( "Entering palm_installer::install_files_by_handheld_dest function" ) );

    // If wxArrayString is empty, then abort
    if ( install_fullnames.IsEmpty() )
    {
        wxLogDebug( "Error: no filenames sent to install_files_by_handheld_dest. Aborting..." );
        return false;
    }

    // Look up the user_index of this user_name
    user_index = get_user_index_from_user_name( handheld_dest.user_name );

    if ( get_number_of_users() > 0 )
    {
        destination_rootpath = get_palm_desktop_path() + "/"
                               + get_user_subdirectory( user_index );

        // If installing to card, use that path...
        switch (  handheld_dest.handheld_target_storage_mode )
        {
        case plkrHANDHELD_TARGET_STORAGE_MODE_SD_CARD:
            destination_path = get_translated_handheld_destination_path( destination_rootpath,
                               "SecureDigital (SD) Card",
                               "SecureDigital"
                                                                       );
            break;
        case plkrHANDHELD_TARGET_STORAGE_MODE_MEMORY_STICK:
            destination_path = destination_rootpath + "/Files to Install/Memory Stick";
            break;
        case plkrHANDHELD_TARGET_STORAGE_MODE_COMPACT_FLASH:
            destination_path = destination_rootpath + "/Files to Install/Compact Flash Card";
            break;
        // default is the normal RAM one.
        default:
            destination_path = destination_rootpath + "/Files to Install";
            break;
        }

        // Check the destination rootpath exists. It may not, if it was a newly created
        // user, it may not have its directory yet
        wxLogDebug( "destination_rootpath=" + destination_rootpath );

        // If this is a brand new user, won't have an "Install" subdirectory
        // in his/her directory yet, so create it, if not there yet.
        if ( ! wxDirExists( destination_path ) )
        {
            wxLogDebug( "destination_path not exist, so making..." );

            // If the "Files to Install" doesn't exist, then need to make that, before can
            // make a dir such as "Memory Stick" inside of that.
            if ( ! wxDirExists ( destination_rootpath + "/Files to Install" ) )
            {
                wxMkdir( destination_rootpath + "/Files to Install", 0777 );
            }

            // OK: can now make the SecureDigital (SD) Card or Memory Stick dir
            // if destination is a card (or the "Files to Install" dir if not card).
            wxMkdir( destination_path, 0777 );
        }

        for ( size_t n = 0; n < install_fullnames.GetCount(); n++ )
        {
            wxLogDebug( "Starting loop to install" );
            install_fullname = install_fullnames.Item( n );
            wxLogDebug( "install_fullname=" + install_fullname );
            install_fullname_exists = wxFileExists( install_fullname );

            if ( install_fullname_exists )
            {
                // Get the basename and extension, so it can have the same basename + extension
                // in the install directory.
                wxSplitPath( install_fullname.c_str(), NULL, &destination_basename,
                             &destination_extension );

                destination_fullname = destination_path + "/" + destination_basename
                                       + '.' + destination_extension;

                // Copy the file over.
                if ( wxCopyFile( install_fullname, destination_fullname, TRUE ) )
                {
                    successful = TRUE;
                }
                else
                {
                    wxLogError( "Error: couldn't copy " + install_fullname + " to " + destination_fullname );
                }

            }
            else
            {
                wxLogDebug( "Error: install_fullname " + install_fullname + " doesn't exist" );
            }
        }
    }

    return successful;
}
示例#22
0
int WinEDA_SchematicFrame::LoadOneEEProject(const wxString & FileName, bool IsNew)
/********************************************************************************/
/*
	Routine de chargement d'un projet ( schema principal "Root" et ses
	sous schemas ( hierarchie )
*/
{
BASE_SCREEN *screen, * NextScreen;
EDA_BaseStruct *EEDrawList ;
wxString FullFileName, msg;
bool LibCacheExist = FALSE;
	
	screen = ScreenSch ;
	while( screen )
	{
		if(screen->IsModify()) break;
		screen = screen->Next();
	}

	if ( screen )
	{
		if( ! IsOK(this, _("Clear Schematic Hierarchy (modified!)?")) ) return FALSE;
		if ( ScreenSch->m_FileName != g_DefaultSchematicFileName )
			SetLastProject(ScreenSch->m_FileName);
	}


	screen = ScreenSch ;
	if( ClearProjectDrawList((SCH_SCREEN*) screen) == FALSE ) return(1);

	FullFileName = FileName;
	if( (FullFileName.IsEmpty() ) && !IsNew )
	{
		wxString mask = wxT("*") + g_SchExtBuffer;
		FullFileName = EDA_FileSelector( _("Schematic files:"),
					wxEmptyString,		  			/* Chemin par defaut */
					wxEmptyString,					/* nom fichier par defaut */
					g_SchExtBuffer,		/* extension par defaut */
					mask,				/* Masque d'affichage */
					this,
					wxOPEN,
					TRUE
					);
		if ( FullFileName.IsEmpty() ) return ( FALSE );
	}

	m_CurrentScreen = screen = ActiveScreen = ScreenSch;
	screen->m_CurrentItem = NULL;
	wxSetWorkingDirectory(wxPathOnly(FullFileName) );
	m_CurrentScreen->m_FileName = FullFileName;
	Affiche_Message(wxEmptyString);
	MsgPanel->EraseMsgBox();

	memset( &g_EESchemaVar,0, sizeof(g_EESchemaVar) );

	m_CurrentScreen->ClrModify();
	m_CurrentScreen->Pnext = NextScreen = NULL;

	if( IsNew )
	{
		screen->m_CurrentSheet = &g_Sheet_A4;
		screen->SetZoom(32);
		screen->m_SheetNumber = screen->m_NumberOfSheet = 1;
		screen->m_Title = wxT("noname.sch");
		m_CurrentScreen->m_FileName = screen->m_Title;
		screen->m_Company.Empty();
		screen->m_Commentaire1.Empty();
		screen->m_Commentaire2.Empty();
		screen->m_Commentaire3.Empty();
		screen->m_Commentaire4.Empty();
		Read_Config(wxEmptyString, TRUE);
		Zoom_Automatique(TRUE);
		ReDrawPanel();
		return (1);
	}
	// Rechargement de la configuration:
	msg = _("Ready\nWorking dir: \n") + wxGetCwd();
	PrintMsg(msg);

	Read_Config(wxEmptyString, FALSE);

	// Delete old caches.
LibraryStruct *nextlib, *lib = g_LibraryList;
	for (; lib != NULL; lib = nextlib )
	{
		nextlib = lib->m_Pnext;
		if ( lib->m_IsLibCache )
			FreeCmpLibrary(this, lib->m_Name);
	}

	if( IsNew )
	{
		ReDrawPanel();
		return (1);
	}

	// Loading the project library cache
	wxString FullLibName;
	wxString shortfilename;
	wxSplitPath(ScreenSch->m_FileName, NULL, &shortfilename, NULL);
	FullLibName << wxT(".") << STRING_DIR_SEP << shortfilename << wxT(".cache") << g_LibExtBuffer;
	if ( wxFileExists(FullLibName) )
	{
		wxString libname;
		libname = FullLibName;
		ChangeFileNameExt(libname,wxEmptyString);
		msg = wxT("Load ") + FullLibName;
		LibraryStruct *LibCache = LoadLibraryName(this, FullLibName, libname);
		if ( LibCache )
		{
			LibCache->m_IsLibCache = TRUE;
			msg += wxT(" OK");
		}
		else msg += wxT(" ->Error");
		PrintMsg( msg );
		LibCacheExist = TRUE;
	}

	if ( ! wxFileExists(screen->m_FileName) && !LibCacheExist)	// Nouveau projet prpbablement
	{
		msg.Printf( _("File %s not found (new project ?)"),
			screen->m_FileName.GetData() );
		DisplayInfo(this, msg, 20);
		return (-1);
	}
	
	if( LoadOneEEFile(screen, screen->m_FileName) == FALSE) return (0);

	/* Chargement des sous feuilles */
	while(screen)
		{
		EEDrawList = screen->EEDrawList;
		while(EEDrawList)
			{
			if( EEDrawList->m_StructType == DRAW_SHEET_STRUCT_TYPE)
				{
				#undef STRUCT
				#define STRUCT ((DrawSheetStruct*)EEDrawList)
				int timestamp = STRUCT->m_TimeStamp;
				if(timestamp == 0 )
					{
					timestamp = GetTimeStamp();
					STRUCT->m_TimeStamp = timestamp;
					}
				if( screen->Pnext == NULL)	/* 1ere Sheet */
					{
					screen->Pnext = NextScreen =
									CreateNewScreen(this, (SCH_SCREEN*)screen,timestamp);
					}
				else
					{
					NextScreen->Pnext = CreateNewScreen(this, (SCH_SCREEN*)NextScreen, timestamp);
					NextScreen = (BASE_SCREEN*)NextScreen->Pnext;
					}

				STRUCT->m_Son = NextScreen;
				NextScreen->m_Parent = EEDrawList;

				if( ! STRUCT->m_Field[SHEET_FILENAME].m_Text.IsEmpty() )
				{
					NextScreen->m_FileName = STRUCT->m_Field[SHEET_FILENAME].m_Text;
					if( LoadOneEEFile(NextScreen, NextScreen->m_FileName) == TRUE )
					{
						ActiveScreen = (SCH_SCREEN*) NextScreen;
					}
				}
				else DisplayError(this, _("No FileName in SubSheet"));
				}
			EEDrawList = EEDrawList->Pnext;
			}
		screen = (BASE_SCREEN*)screen->Pnext;
		}


	/* Reaffichage ecran de base (ROOT) si necessaire */
	screen = ActiveScreen = ScreenSch;
	Zoom_Automatique(FALSE);

	return (1);
}
void main_listctrl::load_rows()
{
    wxString channel_section;   // Section of channel in configuration file
    int row_number           = 0;     // List row to insert channel information    
    long index               = 0;     // Index counter for looping through the sections
    bool found_section       = FALSE; // To monitor success of getting first/next group
    
    wxLogDebug( "Starting to load channel sections into listctrl rows" );
    
    // Make a "channels" directory to hold home.html, cache and other future stuff
    // for each entry
    if ( ! wxDirExists( get_plucker_directory( CHANNELS ) ) ) {
        wxMkdir( get_plucker_directory( CHANNELS ), 0777);
    }
    wxLogDebug( "Finished testing/trying to make channel directory" );
    
    // TODO: also make the default channel one, in case it is gone.
    
    found_section = the_configuration->GetFirstGroup( channel_section,
                                                      index );
    while ( found_section ) {
        // Load up the each channel section (group) from the
        // plucker.ini/pluckerrc file
        wxLogDebug( "Config section=%s", channel_section.c_str() );

       if ( is_channel_section( channel_section ) ) {
            // TODO: check for illegal characters in 
            // section name, and rename the section in the config file
            // as necessary before loading it into listctrl.
            
            // TODO: End these depreciated keys, and merge this to insert_row() function
            
            wxString doc_name;

            doc_name = channel_section + "/doc_name";
            
            // If no doc_name key, then use the db_name key
            // The db_name key is the depreciated equivalent of doc_name key
            if ( ! the_configuration->Exists( doc_name ) )
                doc_name = channel_section + "/db_name";
            
            // If no db_name key either, the the doc_file key as the doc_name also
            if ( ! the_configuration->Exists( doc_name ) ) 
                doc_name = channel_section + "/doc_file";
            
            // The no db_name or doc_file key, then use the db_file key.
            // The db_file key is the depreciated equivalent of doc_file key
            if ( ! the_configuration->Exists( doc_name ) ) 
                doc_name = channel_section + "/db_file";
                                      
            // Only include channels with an assigned document name
            if ( the_configuration->Exists( doc_name ) ) {
                wxString channel_name;
                wxString due_date;
                
                // Read the current channel name, from configuration file, 
                // or generate a channel name based on values or /doc_file or 
                // /db_file 
                channel_name = the_configuration->Read( doc_name,
                                                        _( "Unnamed Channel" ) );
                                                        
                // Write a doc_name key, since the depreciated ones aren't going
                // to be looked for after this
                the_configuration->Write( '/' + channel_section + '/' + "doc_name",
                                          channel_name );
                
                // If it was a filename key, then strip off path and the 
                // extension, so only basename left
                if ( doc_name == channel_section + "/doc_file" ||
                     doc_name == channel_section + "/db_file" ) {
                    wxSplitPath( channel_name.c_str(), NULL, &channel_name, NULL ); 
                }
                // Insert a new row (item in wxWindows) in the listctrl using
                // the channel_name value as the string in the 1st column. The
                // 3rd argument of InsertItem is the image index of the shared
                // image list (called 'the_small_image_list'). This 3rd argument
                // creates a little glyph for the row.
                InsertItem( row_number, channel_name,
                            SMALL_IMAGE_LIST_ID_MAIN_DIALOG_LISTCTRL );   

                // Read the due date and put it in its column.       
                wxDateTime  due_datetime;
                wxString    due_string;

                due_datetime   = the_plucker_controller->get_channel_due_datetime( channel_section );    
                due_string     = due_datetime.Format( wxT( plkrPRETTY_COMPACT_DATE_TIME_FORMAT ) ).c_str();                   

                if ( ! the_plucker_controller->is_channel_update_enabled( channel_section ) ) {
                    due_string = _( "Never" );
                }                                               
                
                SetItem( row_number, DUE_COLUMN, due_string );     
            
                // Put the section_name into SECTION column so know what section
                // of configuration file to call when configure/update the channel.
                SetItem( row_number, SECTION_COLUMN, channel_section );
            
                // Make a "channel" and a "channel/cache" directory for each entry,
                // and making a home.html and exclusionlist.txt if there isn't one.
                the_plucker_controller->create_new_channel_subdirectory( channel_section );
            
                // Increase the row number where we will insert new one.            
                row_number++;
            }
        }
        found_section = the_configuration->GetNextGroup( channel_section,
                                                         index );
    }
}
示例#24
0
/****************************************************************************
PARAMETERS:
URL - New URL for the page to load

RETURNS:
True if page loaded successfully, false if not

REMARKS:
Remove an applet from the manager. Called during applet destruction
****************************************************************************/
bool wxHtmlAppletWindow::LoadPage(
    const wxString& link)
{
    wxString href(link);

    if (link.GetChar(0) == '?'){
        wxString cmd = link.BeforeFirst('=');
        wxString cmdValue = link.AfterFirst('=');

        // Launches the default Internet browser for the system.
        if(!(cmd.CmpNoCase("?EXTERNAL"))) {
            return wxSpawnBrowser(this, cmdValue.c_str());
            }

        // Launches an external program on the system.
        if (!(cmd.CmpNoCase("?EXECUTE"))) {
            int waitflag = P_NOWAIT;
            bool ret;
            wxString currentdir;
            wxString filename, path, ext;

            // Parse the params sent to the execute command. For now the only
            // parm is "wait". wait will cause spawn wait, default is nowait.
            // Since we only need one param for now I am not going to make this
            // any smater then it needs to be. If we need more params later i'll
            // fix it.
            int i = cmdValue.Find('(');
            if (i != -1) {
                wxString param = cmdValue.AfterFirst('(');
                cmdValue.Truncate(i);
                if (!param.CmpNoCase("wait)"))
                    waitflag = P_WAIT;
                }

            currentdir = wxGetCwd();
            //we don't want to change the path of the virtual file system so we have to use these
            //functions rather than the filesystem
            wxSplitPath(cmdValue, &path, &filename, &ext);
            if (path.CmpNoCase("") != 0) wxSetWorkingDirectory(path);

            ret = !spawnl( waitflag, cmdValue , NULL );
            //HACK should use wxExecute
            //ret = wxExecute(filename, bool sync = FALSE, wxProcess *callback = NULL)
            wxSetWorkingDirectory(currentdir);

            return ret;
            }

        // Looks for a href in a variable stored as a cookie. The href can be
        // changed on the fly.
        if (!(cmd.CmpNoCase("?VIRTUAL"))){
            wxObject *obj = FindCookie(cmdValue);
            VirtualData *virtData = wxDynamicCast(obj,VirtualData);
            if (virtData) {
                // recurse and loadpage, just in case the link is like another
                // ? link
                return LoadPage(virtData->GetHref());
                }
            else {
#ifdef CHECKED
                wxLogError(_T("VIRTUAL LINK ERROR: '%s' does not exist."), cmdValue.c_str());
#endif
                return true;
                }
            }

        // This launches a qlet - It is like an applet but is more generic in that it
        // can be of any wxWin type so it then has the freedom to do more stuff.
        if (!(cmd.CmpNoCase("?WXPLUGIN"))){
            if (!cmdValue.IsNull()) {
                // TODO: We are going to need to add code to parse the command line
                //       parameters string in here in the future...
                wxString cmdLine = link.AfterFirst('(');
                cmdLine = cmdLine.BeforeLast(')');
                if (!CreatePlugIn(cmdValue,cmdLine)) {
#ifdef CHECKED
                    wxLogError(_T("Launch PlugIn ERROR: '%s' does not exist."), cmdValue.c_str());
#endif
                    }
                }
             return true;
            }

        // This used in a link or href will take you back in the history.
        if (!(cmd.CmpNoCase("?BACK"))){
            HistoryBack();
            return true;
            }

        // This used in a link or href will take you forward in the history
        if (!(cmd.CmpNoCase("?FORWARD"))){
            HistoryForward();
            return true;
            }
        }

    // Inform all the applets that the new page is being loaded
    for (wxAppletList::Node *node = m_AppletList.GetFirst(); node; node = node->GetNext())
        (node->GetData())->OnLinkClicked(wxHtmlLinkInfo(href));
    Show(false);

    m_openedlast = href;
    bool stat = wxHtmlWindow::LoadPage(href);
    Show(true);

    // Enable/Dis the navbar tools
    if (m_NavBarEnabled) {
        m_NavBar->EnableTool(m_NavForwardId,HistoryCanForward());
        m_NavBar->EnableTool(m_NavBackId,HistoryCanBack());
        }
    return stat;
}
示例#25
0
文件: filedlg.cpp 项目: Duion/Torsion
int wxFileDialog::ShowModal()
{
    wxString                        sTheFilter;
    wxString                        sFilterBuffer;
    wxChar*                         pzFilterBuffer;
    static wxChar                   zFileNameBuffer[wxMAXPATH];           // the file-name
    HWND                            hWnd = 0;
    wxChar                          zTitleBuffer[wxMAXFILE + 1 + wxMAXEXT];  // the file-name, without path
    wxString                        sDir;
    size_t                          i;
    size_t                          nLen = m_dir.length();
    int                             nCount = 0;
    FILEDLG                         vFileDlg;
    ULONG                           lFlags = 0L;

    memset(&vFileDlg, '\0', sizeof(FILEDLG));
    if (m_parent)
        hWnd = (HWND) m_parent->GetHWND();
    if (!hWnd && wxTheApp->GetTopWindow())
        hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();


    *zFileNameBuffer = wxT('\0');
    *zTitleBuffer    = wxT('\0');

    if (m_dialogStyle & wxSAVE)
        lFlags = FDS_SAVEAS_DIALOG;
    else
        lFlags = FDS_OPEN_DIALOG;

#if WXWIN_COMPATIBILITY_2_4
    if (m_dialogStyle & wxHIDE_READONLY)
        lFlags |= FDS_SAVEAS_DIALOG;
#endif

    if (m_dialogStyle & wxSAVE)
        lFlags |= FDS_SAVEAS_DIALOG;
    if (m_dialogStyle & wxMULTIPLE )
        lFlags |= FDS_OPEN_DIALOG | FDS_MULTIPLESEL;

    vFileDlg.cbSize = sizeof(FILEDLG);
    vFileDlg.fl = lFlags;
    vFileDlg.pszTitle = (PSZ)zTitleBuffer;

    //
    // Convert forward slashes to backslashes (file selector doesn't like
    // forward slashes) and also squeeze multiple consecutive slashes into one
    // as it doesn't like two backslashes in a row neither
    //
    sDir.reserve(nLen);
    for ( i = 0; i < nLen; i++ )
    {
        wxChar                      ch = m_dir[i];

        switch (ch)
        {
            case _T('/'):
                //
                // Convert to backslash
                //
                ch = _T('\\');

                //
                // Fall through
                //
            case _T('\\'):
                while (i < nLen - 1)
                {
                    wxChar          chNext = m_dir[i + 1];

                    if (chNext != _T('\\') && chNext != _T('/'))
                        break;

                    //
                    // Ignore the next one, unless it is at the start of a UNC path
                    //
                    if (i > 0)
                        i++;
                    else
                        break;
                }

                //
                // Fall through
                //

            default:
                //
                // Normal char
                sDir += ch;
        }
    }
    if ( wxStrlen(m_wildCard) == 0 )
        sTheFilter = wxEmptyString;
    else
        sTheFilter = m_wildCard;

    wxStrtok((wxChar*)sTheFilter.c_str(), wxT("|"), &pzFilterBuffer);
    while(pzFilterBuffer != NULL)
    {
        if (nCount > 0 && !(nCount % 2))
            sDir += wxT(";");
        if (nCount % 2)
        {
            sDir += pzFilterBuffer;
        }
        wxStrtok(NULL, wxT("|"), &pzFilterBuffer);
        nCount++;
    }
    if (nCount == 0)
        sDir += m_fileName;
    if (sDir.empty())
        sDir = wxT("*.*");
    wxStrcpy((wxChar*)vFileDlg.szFullFile, sDir);
    sFilterBuffer = sDir;

    hWnd = ::WinFileDlg( HWND_DESKTOP
                        ,GetHwndOf(m_parent)
                        ,&vFileDlg
                       );
    if (hWnd && vFileDlg.lReturn == DID_OK)
    {
        m_fileNames.Empty();
        if ((m_dialogStyle & wxMULTIPLE ) && vFileDlg.ulFQFCount > 1)
        {
            for (int i = 0; i < (int)vFileDlg.ulFQFCount; i++)
            {
                if (i == 0)
                {
                    m_dir = wxPathOnly(wxString((const wxChar*)*vFileDlg.papszFQFilename[0]));
                    m_path = (const wxChar*)*vFileDlg.papszFQFilename[0];
                }
                m_fileName = wxFileNameFromPath(wxString((const wxChar*)*vFileDlg.papszFQFilename[i]));
                m_fileNames.Add(m_fileName);
            }
            ::WinFreeFileDlgList(vFileDlg.papszFQFilename);
        }
        else if (!(m_dialogStyle & wxSAVE))
        {
            m_path = (wxChar*)vFileDlg.szFullFile;
            m_fileName = wxFileNameFromPath(wxString((const wxChar*)vFileDlg.szFullFile));
            m_dir = wxPathOnly((const wxChar*)vFileDlg.szFullFile);
        }
        else // save file
        {
            const wxChar*           pzExtension = NULL;

            wxStrcpy(zFileNameBuffer, (const wxChar*)vFileDlg.szFullFile);

            int                     nIdx = wxStrlen(zFileNameBuffer) - 1;
            wxString                sExt;

            wxSplitPath( zFileNameBuffer
                        ,&m_path
                        ,&m_fileName
                        ,&sExt
                       );
            if (zFileNameBuffer[nIdx] == wxT('.') || sExt.empty())
            {
                zFileNameBuffer[nIdx] = wxT('\0');

                //
                // User has typed a filename without an extension:
                //
                // A filename can end in a "." here ("abc."), this means it
                // does not have an extension. Because later on a "." with
                // the default extension is appended we remove the "." if
                // filename ends with one (We don't want files called
                // "abc..ext")
                //
                pzExtension = sFilterBuffer.c_str();

                for( int i = 0; i < (int)sFilterBuffer.length(); i++ )
                {
                    //
                    // Get extension
                    //
                    pzExtension = wxStrrchr(pzExtension, wxT('.'));
                    if ( pzExtension                      &&
                        !wxStrrchr(pzExtension, wxT('*')) &&
                        !wxStrrchr(pzExtension, wxT('?')) &&
                        pzExtension[1]                    &&
                        pzExtension[1] != wxT(' ')
                       )              // != "blabla. "
                    {
                        //
                        // Now concat extension to the fileName:
                        //
                        m_path = wxString(zFileNameBuffer) + pzExtension;
                    }
                }
            }
            else
            {
                m_path = (wxChar*)vFileDlg.szFullFile;
            }
            m_fileName = wxFileNameFromPath((const wxChar*)vFileDlg.szFullFile);
            m_dir = wxPathOnly((const wxChar*)vFileDlg.szFullFile);

            //
            // === Simulating the wxOVERWRITE_PROMPT >>============================
            //
            if ((m_dialogStyle & wxOVERWRITE_PROMPT) &&
                (m_dialogStyle & wxSAVE) &&
                (wxFileExists(m_path.c_str())))
            {
                wxString            sMessageText;

                sMessageText.Printf( _("File '%s' already exists.\nDo you want to replace it?")
                                    ,m_path.c_str()
                                   );
                if (wxMessageBox( sMessageText
                                 ,wxT("Save File As")
                                 ,wxYES_NO | wxICON_EXCLAMATION
                                ) != wxYES)
                {
                    return wxID_CANCEL;
                }
            }
        }
        return wxID_OK;
    }
    return wxID_CANCEL;
} // end of wxFileDialog::ShowModal
// When a "Choose file..." button beside a filename textctrl is clicked, show
// a filename dialog, initialize to textctrl's previous value if possible, get the
// filename and  put it back in the textctrl. Return FALSE if there was a problem.
bool utils_controls::textctrl_filename_selection 
    ( 
    wxTextCtrl* target_filename_textctrl,       // TextCtrl to read/write filename(s)
    wxString message,                           // Message for the textctrl
    wxString default_file,                      // Default filename
    wxString default_directory,                 // Default directory
    wxString wildcard,                          // Wildcard filters
    bool allow_multiple,                        // Allow multiple selections
    wxChar multiple_selection_delimiter,        // Delimiter in textctrl to use to 
                                                // separate multiple files (usu ;)
    bool uses_file_protocol                     // Whether to remove a potiential "file://" or
                                                // prefix from the incoming string, then add 
                                                // to output.
    )
{


    // Extract the old filename value to override default file and default directory
    wxString old_filename_string = target_filename_textctrl->GetValue();   
    if ( allow_multiple == TRUE ) 
    {
        // Can only use the first entry to set dir/file.
        old_filename_string = old_filename_string.BeforeFirst ( multiple_selection_delimiter );
    }
    
    wxString file_protocol_prefix = wxT( "" );
    
    // It uses_file_protocol flag is on, then strip off any leading file:// or file:
    // Look for/strip off a "file://" first, then if not one, then look for/strip off 
    // a "file:" prefix next. If no file: either, then keep going. Keep the 
    // file_protocol_prefix so we can tack it on again at the end.
    if ( uses_file_protocol ) 
    {
        if ( old_filename_string.StartsWith( wxT( "file://" ), &old_filename_string ) ) 
        {
            file_protocol_prefix = wxT( "file://" );
        } 
        else 
        {
            if ( old_filename_string.StartsWith( wxT( "file:" ), &old_filename_string ) )
            {
                file_protocol_prefix = wxT( "file:" );
            }
        }    
    }       

    // Get some strings ready to split the path.
    wxString old_directory;
    wxString old_base;
    wxString old_extension;
    
    // Must check for non-null string before calling wxSplitPath
    if ( old_filename_string != wxT( "" ) )
    {
        wxSplitPath( old_filename_string, &old_directory, &old_base, &old_extension );
    }
    
    // If there was a directory part, make that default directory
    if ( old_directory != wxT( "" ) ) 
    {
        default_directory = old_directory;
    }
    
    // If was a base, make that default filename
    if ( old_base != wxT( "" ) ) 
    {
        default_file = old_base;
        // If was an extension, add a '.' and the extension to filename
        if ( old_extension != wxT( "" ) ) {
            default_file += wxT( "." ) + old_extension;
        } 
    }

#if ( setupUSE_NO_CONTROL_PERSISTANCE_HACK )
    // Stop wxFileDialog from saving to plucker.ini by setting the active config
    // to NULL.
    wxConfigBase* previous_configuration = NULL;
    previous_configuration = wxConfigBase::Set( NULL );        
#endif 

    // As of wx2.8, can only set the style on the file dialog before it is created. No later SetStyle()
	// If specified that to allow multiple, then set that flag, otherwise, leave as default.
	long style;
    if ( allow_multiple == TRUE )
    {
        style = wxMULTIPLE;
    }  
	else
	{
		style = wxFD_DEFAULT_STYLE;
	}

    wxFileDialog a_file_dialog( target_filename_textctrl->GetParent(), 
                              message,
                              default_directory,
                              default_file,
                              wildcard, 
							  style );          
                                  
    wxString output_string;
    // Show the filename dialog modally, and only do the action if returned
    // hitting an OK button.
    if ( a_file_dialog.ShowModal() == wxID_OK )
    {
        if ( allow_multiple == TRUE )
        {
            // Get the array of selections, and loop through writing to output_string 
            // and a delimiter at the end of each.
            wxArrayString selected_paths;
            a_file_dialog.GetPaths( selected_paths );
            for ( size_t i=0; i < selected_paths.Count(); i++ ) {
                output_string += selected_paths.Item( i ) + multiple_selection_delimiter;
            }
            selected_paths.Clear(); 
            // Remove the last delimiter
            output_string.RemoveLast();                 
        } 
        else 
        {
            output_string = a_file_dialog.GetPath();
        }
        
        // If flag set to load/save file:// extension, then bolt it back on.
        if ( uses_file_protocol ) 
        {
            output_string = file_protocol_prefix + output_string;
        }
        
        target_filename_textctrl->SetValue( output_string );
    }    

#if ( setupUSE_NO_CONTROL_PERSISTANCE_HACK )
    // Destroy the wxFileDialog to force saving of its settings.
    a_file_dialog.Destroy();
    // Set the active config to the previous one:
    wxConfigBase::Set( previous_configuration );
#endif
    
    return TRUE;
}
示例#27
0
bool wxXPMHandler::SaveFile(wxImage * image,
                            wxOutputStream& stream, bool WXUNUSED(verbose))
{
    // 1. count colours:
    #define MaxCixels  92
    static const char Cixel[MaxCixels+1] =
                         " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjk"
                         "lzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|";
    int i, j, k;

    wxImageHistogram histogram;
    int cols = int(image->ComputeHistogram(histogram));

    int chars_per_pixel = 1;
    for ( k = MaxCixels; cols > k; k *= MaxCixels)
        chars_per_pixel++;

    // 2. write the header:
    wxString sName;
    if ( image->HasOption(wxIMAGE_OPTION_FILENAME) )
    {
        wxSplitPath(image->GetOption(wxIMAGE_OPTION_FILENAME),
                    NULL, &sName, NULL);
        sName << wxT("_xpm");
    }

    if ( !sName.empty() )
        sName = wxString(wxT("/* XPM */\nstatic const char *")) + sName;
    else
        sName = wxT("/* XPM */\nstatic const char *xpm_data");
    stream.Write( (const char*) sName.ToAscii(), sName.Len() );

    char tmpbuf[200];
    // VS: 200b is safe upper bound for anything produced by sprintf below
    //     (<101 bytes the string, neither %i can expand into more than 10 chars)
    sprintf(tmpbuf,
               "[] = {\n"
               "/* columns rows colors chars-per-pixel */\n"
               "\"%i %i %i %i\",\n",
               image->GetWidth(), image->GetHeight(), cols, chars_per_pixel);
    stream.Write(tmpbuf, strlen(tmpbuf));

    // 3. create color symbols table:
    char *symbols_data = new char[cols * (chars_per_pixel+1)];
    char **symbols = new char*[cols];

    // 2a. find mask colour:
    unsigned long mask_key = 0x1000000 /*invalid RGB value*/;
    if (image->HasMask())
        mask_key = (image->GetMaskRed() << 16) |
                   (image->GetMaskGreen() << 8) | image->GetMaskBlue();

    // 2b. generate colour table:
    for (wxImageHistogram::iterator entry = histogram.begin();
         entry != histogram.end(); ++entry )
    {
        unsigned long index = entry->second.index;
        symbols[index] = symbols_data + index * (chars_per_pixel+1);
        char *sym = symbols[index];

        for (j = 0; j < chars_per_pixel; j++)
        {
            sym[j] = Cixel[index % MaxCixels];
            index /= MaxCixels;
        }
        sym[j] = '\0';

        unsigned long key = entry->first;

        if (key == 0)
            sprintf( tmpbuf, "\"%s c Black\",\n", sym);
        else if (key == mask_key)
            sprintf( tmpbuf, "\"%s c None\",\n", sym);
        else
        {
            wxByte r = wxByte(key >> 16);
            wxByte g = wxByte(key >> 8);
            wxByte b = wxByte(key);
            sprintf(tmpbuf, "\"%s c #%02X%02X%02X\",\n", sym, r, g, b);
        }
        stream.Write( tmpbuf, strlen(tmpbuf) );
    }

    stream.Write("/* pixels */\n", 13);

    unsigned char *data = image->GetData();
    for (j = 0; j < image->GetHeight(); j++)
    {
        char tmp_c;
        tmp_c = '\"'; stream.Write(&tmp_c, 1);
        for (i = 0; i < image->GetWidth(); i++, data += 3)
        {
            unsigned long key = (data[0] << 16) | (data[1] << 8) | (data[2]);
            stream.Write(symbols[histogram[key].index], chars_per_pixel);
        }
        tmp_c = '\"'; stream.Write(&tmp_c, 1);
        if ( j + 1 < image->GetHeight() )
        {
            tmp_c = ','; stream.Write(&tmp_c, 1);
        }
        tmp_c = '\n'; stream.Write(&tmp_c, 1);
    }
    stream.Write("};\n", 3 );

    // Clean up:
    delete[] symbols;
    delete[] symbols_data;

    return true;
}
示例#28
0
// this function is called a *lot* of times (as I learned after seeing from
// profiler output that it is called ~12000 times from Mahogany start up code!)
// so it is important to optimize it - in particular, avoid using generic
// string functions here and do everything manually because it is faster
//
// I still kept the old version to be able to check that the optimized code has
// the same output as the non optimized version.
void wxRegConfig::SetPath(const wxString& strPath)
{
    // remember the old path
    wxString strOldPath = m_strPath;

#ifdef WX_DEBUG_SET_PATH // non optimized version kept here for testing
    wxString m_strPathAlt;

    {
        wxArrayString aParts;

        // because GetPath() returns "" when we're at root, we must understand
        // empty string as "/"
        if ( strPath.empty() || (strPath[0] == wxCONFIG_PATH_SEPARATOR) ) {
            // absolute path
            wxSplitPath(aParts, strPath);
        }
        else {
            // relative path, combine with current one
            wxString strFullPath = GetPath();
            strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
            wxSplitPath(aParts, strFullPath);
        }

        // recombine path parts in one variable
        wxString strRegPath;
        m_strPathAlt.Empty();
        for ( size_t n = 0; n < aParts.Count(); n++ ) {
            strRegPath << '\\' << aParts[n];
            m_strPathAlt << wxCONFIG_PATH_SEPARATOR << aParts[n];
        }
    }
#endif // 0

    // check for the most common case first
    if ( strPath.empty() )
    {
        m_strPath = wxCONFIG_PATH_SEPARATOR;
    }
    else // not root
    {
        // construct the full path
        wxString strFullPath;
        if ( strPath[0u] == wxCONFIG_PATH_SEPARATOR )
        {
            // absolute path
            strFullPath = strPath;
        }
        else // relative path
        {
            strFullPath.reserve(2*m_strPath.length());

            strFullPath << m_strPath;
            if ( strFullPath.Len() == 0 ||
                 strFullPath.Last() != wxCONFIG_PATH_SEPARATOR )
                strFullPath << wxCONFIG_PATH_SEPARATOR;
            strFullPath << strPath;
        }

        // simplify it: we need to handle ".." here

        // count the total number of slashes we have to know if we can go upper
        size_t totalSlashes = 0;

        // position of the last slash to be able to backtrack to it quickly if
        // needed, but we set it to -1 if we don't have a valid position
        //
        // we only remember the last position which means that we handle ".."
        // quite efficiently but not "../.." - however the latter should be
        // much more rare, so it is probably ok
        int posLastSlash = -1;

        const wxChar *src = strFullPath.c_str();
        size_t len = strFullPath.length();
        const wxChar *end = src + len;

        wxStringBufferLength buf(m_strPath, len);
        wxChar *dst = buf;
        wxChar *start = dst;

        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
            {
                // check for "/.."

                // note that we don't have to check for src < end here as
                // *end == 0 so can't be '.'
                if ( src[1] == wxT('.') && src[2] == wxT('.') &&
                     (src + 3 == end || src[3] == wxCONFIG_PATH_SEPARATOR) )
                {
                    if ( !totalSlashes )
                    {
                        wxLogWarning(_("'%s' has extra '..', ignored."),
                                     strFullPath.c_str());
                    }
                    else // return to the previous path component
                    {
                        // do we already have its position?
                        if ( posLastSlash == -1 )
                        {
                            // no, find it: note that we are sure to have one
                            // because totalSlashes > 0 so we don't have to
                            // check the boundary condition below

                            // this is more efficient than strrchr()
                            dst--;
                            while ( *dst != wxCONFIG_PATH_SEPARATOR )
                            {
                                dst--;
                            }
                        }
                        else // the position of last slash was stored
                        {
                            // go directly there
                            dst = start + posLastSlash;

                            // invalidate posLastSlash
                            posLastSlash = -1;
                        }

                        // we must have found a slash one way or another!
                        wxASSERT_MSG( *dst == wxCONFIG_PATH_SEPARATOR,
                                      wxT("error in wxRegConfig::SetPath") );

                        // stay at the same position
                        dst--;

                        // we killed one
                        totalSlashes--;
                    }

                    // skip both dots
                    src += 2;
                }
                else // not "/.."
                {
                    if ( (dst == start) || (dst[-1] != wxCONFIG_PATH_SEPARATOR) )
                    {
                        *dst = wxCONFIG_PATH_SEPARATOR;

                        posLastSlash = dst - start;

                        totalSlashes++;
                    }
                    else // previous char was a slash too
                    {
                        // squeeze several subsequent slashes into one: i.e.
                        // just ignore this one
                        dst--;
                    }
                }
            }
            else // normal character
            {
                // just copy
                *dst = *src;
            }
        }

        // NUL terminate the string
        if ( dst[-1] == wxCONFIG_PATH_SEPARATOR && (dst != start + 1) )
        {
            // if it has a trailing slash we remove it unless it is the only
            // string character
            dst--;
        }

        *dst = wxT('\0');
        buf.SetLength(dst - start);
    }

#ifdef WX_DEBUG_SET_PATH
    wxASSERT( m_strPath == m_strPathAlt );
#endif

    if ( m_strPath == strOldPath )
        return;

    // registry APIs want backslashes instead of slashes
    wxString strRegPath;
    if ( !m_strPath.empty() )
    {
        size_t len = m_strPath.length();

        const wxChar *src = m_strPath.c_str();
        wxStringBufferLength buf(strRegPath, len);
        wxChar *dst = buf;

        const wxChar *end = src + len;
        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
                *dst = wxT('\\');
            else
                *dst = *src;
        }

        buf.SetLength(len);
    }

    // this is not needed any longer as we don't create keys unnecessarily any
    // more (now it is done on demand, i.e. only when they're going to contain
    // something)
#if 0
    // as we create the registry key when SetPath(key) is done, we can be left
    // with plenty of empty keys if this was only done to try to read some
    // value which, in fact, doesn't exist - to prevent this from happening we
    // automatically delete the old key if it was empty
    if ( m_keyLocal.Exists() && LocalKey().IsEmpty() )
    {
        m_keyLocal.DeleteSelf();
    }
#endif // 0

    // change current key(s)
    m_keyLocal.SetName(m_keyLocalRoot, strRegPath);

    if ( GetStyle() & wxCONFIG_USE_GLOBAL_FILE )
    {
      m_keyGlobal.SetName(m_keyGlobalRoot, strRegPath);

      wxLogNull nolog;
      m_keyGlobal.Open(wxRegKey::Read);
    }
}
示例#29
0
void wxFileData::ReadData()
{
    if (IsDrive())
    {
        m_size = 0;
        return;
    }

#if defined(__DOS__) || (defined(__WINDOWS__) && !defined(__WXWINCE__)) || defined(__OS2__)
    // c:\.. is a drive don't stat it
    if ((m_fileName == wxT("..")) && (m_filePath.length() <= 5))
    {
        m_type = is_drive;
        m_size = 0;
        return;
    }
#endif // __DOS__ || __WINDOWS__

#ifdef __WXWINCE__

    // WinCE

    DWORD fileAttribs = GetFileAttributes(m_filePath.fn_str());
    m_type |= (fileAttribs & FILE_ATTRIBUTE_DIRECTORY) != 0 ? is_dir : 0;

    wxString p, f, ext;
    wxSplitPath(m_filePath, & p, & f, & ext);
    if (wxStricmp(ext, wxT("exe")) == 0)
        m_type |= is_exe;

    // Find out size
    m_size = 0;
    HANDLE fileHandle = CreateFile(m_filePath.fn_str(),
                                   GENERIC_READ,
                                   FILE_SHARE_READ,
                                   NULL,
                                   OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL,
                                   NULL);

    if (fileHandle != INVALID_HANDLE_VALUE)
    {
        m_size = GetFileSize(fileHandle, 0);
        CloseHandle(fileHandle);
    }

    m_dateTime = wxFileModificationTime(m_filePath);

#else

    // OTHER PLATFORMS

    wxStructStat buff;

#if defined(__UNIX__) && (!defined( __OS2__ ) && !defined(__VMS))
    lstat( m_filePath.fn_str(), &buff );
    m_type |= S_ISLNK( buff.st_mode ) != 0 ? is_link : 0;
#else // no lstat()
    // only translate to file charset if we don't go by our
    // wxStat implementation
#ifndef wxNEED_WX_UNISTD_H
    wxStat( m_filePath.fn_str() , &buff );
#else
    wxStat( m_filePath, &buff );
#endif
#endif

    m_type |= (buff.st_mode & S_IFDIR) != 0 ? is_dir : 0;
    m_type |= (buff.st_mode & wxS_IXUSR) != 0 ? is_exe : 0;
    m_size = (long)buff.st_size;

    m_dateTime = buff.st_mtime;
#endif
    // __WXWINCE__

#if defined(__UNIX__)
    m_permissions.Printf(_T("%c%c%c%c%c%c%c%c%c"),
                         buff.st_mode & wxS_IRUSR ? _T('r') : _T('-'),
                         buff.st_mode & wxS_IWUSR ? _T('w') : _T('-'),
                         buff.st_mode & wxS_IXUSR ? _T('x') : _T('-'),
                         buff.st_mode & wxS_IRGRP ? _T('r') : _T('-'),
                         buff.st_mode & wxS_IWGRP ? _T('w') : _T('-'),
                         buff.st_mode & wxS_IXGRP ? _T('x') : _T('-'),
                         buff.st_mode & wxS_IROTH ? _T('r') : _T('-'),
                         buff.st_mode & wxS_IWOTH ? _T('w') : _T('-'),
                         buff.st_mode & wxS_IXOTH ? _T('x') : _T('-'));
#elif defined(__WIN32__)
    DWORD attribs = GetFileAttributes(m_filePath.fn_str());
    if (attribs != (DWORD)-1)
    {
        m_permissions.Printf(_T("%c%c%c%c"),
                             attribs & FILE_ATTRIBUTE_ARCHIVE  ? _T('A') : _T(' '),
                             attribs & FILE_ATTRIBUTE_READONLY ? _T('R') : _T(' '),
                             attribs & FILE_ATTRIBUTE_HIDDEN   ? _T('H') : _T(' '),
                             attribs & FILE_ATTRIBUTE_SYSTEM   ? _T('S') : _T(' '));
    }
#endif

    // try to get a better icon
    if (m_image == wxFileIconsTable::file)
    {
        if (m_fileName.Find(wxT('.'), true) != wxNOT_FOUND)
        {
            m_image = wxTheFileIconsTable->GetIconID( m_fileName.AfterLast(wxT('.')));
        } else if (IsExe())
        {
            m_image = wxFileIconsTable::executable;
        }
    }
}
示例#30
0
文件: utils.cpp 项目: 252525fb/rpcs3
const wxChar* wxGetHomeDir(wxString *pstr)
{
    wxString& strDir = *pstr;

    // first branch is for Cygwin
#if defined(__UNIX__) && !defined(__WINE__)
    const wxChar *szHome = wxGetenv("HOME");
    if ( szHome == NULL ) {
      // we're homeless...
      wxLogWarning(_("can't find user's HOME, using current directory."));
      strDir = wxT(".");
    }
    else
       strDir = szHome;

    // add a trailing slash if needed
    if ( strDir.Last() != wxT('/') )
      strDir << wxT('/');

    #ifdef __CYGWIN__
        // Cygwin returns unix type path but that does not work well
        static wxChar windowsPath[MAX_PATH];
        cygwin_conv_to_full_win32_path(strDir, windowsPath);
        strDir = windowsPath;
    #endif
#elif defined(__WXWINCE__)
    strDir = wxT("\\");
#else
    strDir.clear();

    // If we have a valid HOME directory, as is used on many machines that
    // have unix utilities on them, we should use that.
    const wxChar *szHome = wxGetenv(wxT("HOME"));

    if ( szHome != NULL )
    {
        strDir = szHome;
    }
    else // no HOME, try HOMEDRIVE/PATH
    {
        szHome = wxGetenv(wxT("HOMEDRIVE"));
        if ( szHome != NULL )
            strDir << szHome;
        szHome = wxGetenv(wxT("HOMEPATH"));

        if ( szHome != NULL )
        {
            strDir << szHome;

            // the idea is that under NT these variables have default values
            // of "%systemdrive%:" and "\\". As we don't want to create our
            // config files in the root directory of the system drive, we will
            // create it in our program's dir. However, if the user took care
            // to set HOMEPATH to something other than "\\", we suppose that he
            // knows what he is doing and use the supplied value.
            if ( wxStrcmp(szHome, wxT("\\")) == 0 )
                strDir.clear();
        }
    }

    if ( strDir.empty() )
    {
        // If we have a valid USERPROFILE directory, as is the case in
        // Windows NT, 2000 and XP, we should use that as our home directory.
        szHome = wxGetenv(wxT("USERPROFILE"));

        if ( szHome != NULL )
            strDir = szHome;
    }

    if ( !strDir.empty() )
    {
        // sometimes the value of HOME may be "%USERPROFILE%", so reexpand the
        // value once again, it shouldn't hurt anyhow
        strDir = wxExpandEnvVars(strDir);
    }
    else // fall back to the program directory
    {
        // extract the directory component of the program file name
        wxSplitPath(wxGetFullModuleName(), &strDir, NULL, NULL);
    }
#endif  // UNIX/Win

    return strDir.c_str();
}