예제 #1
0
bool CMusikLibrary::UpdateSongDataFromFile( const wxString & filename , bool bForce)
{
	if ( filename.IsEmpty() )
		return false;
    if(!bForce)
    {
        double jdnFileInDbMTIME;

        if(m_pDB->Exec(MusikDb::QueryString( "select songs.modified from songs where filename = %Q;",
            ( const char* )ConvToUTF8(filename) ),&jdnFileInDbMTIME))
        {
            wxStructStat st;
            wxStat(filename,&st);
            wxDateTime dt(st.st_mtime);
            if(dt.GetJDN() <= jdnFileInDbMTIME)
            {// file mtime is less than the modified time in the db entry
                return false;
            }
        }
    }
	CSongMetaData MetaData;
	MetaData.Filename = filename;
	CMetaDataHandler::RetCode rc  = CMetaDataHandler::GetMetaData( MetaData );
	if(rc == CMetaDataHandler::notsupported)
	{
		::wxLogInfo(_("Parsing of file %s not supported. Song data is not updated."),(const wxChar *)MetaData.Filename.GetFullPath());
		return true; // we are not able to parse this file, so we return here, to not overwrite the possible user edited data in the db with empty data.
	}
	if(rc == CMetaDataHandler::success )
	{
		int songid = QueryCount(MusikDb::QueryString( "select distinct songs.songid from songs where filename = %Q;", ( const char* )ConvToUTF8(MetaData.Filename.GetFullPath()) ));
		wxASSERT(songid >= 0);
		UpdateFullSongData(songid,MetaData);
	}
	else if(rc == CMetaDataHandler::fail)
	{
		::wxLogWarning(_("Parsing of file %s failed."),(const wxChar *)MetaData.Filename.GetFullPath());
	}
	else
	{
		wxASSERT(false);
	}
    
	return rc != CMetaDataHandler::fail;
}
예제 #2
0
파일: dir.cpp 프로젝트: czxxjtu/wxPython-1
bool wxDir::HasSubDirs(const wxString& spec) const
{
    wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") );

    if ( spec.empty() )
    {
        // faster check for presence of any subdirectory: normally each subdir
        // has a hard link to the parent directory and so, knowing that there
        // are at least "." and "..", we have a subdirectory if and only if
        // links number is > 2 - this is just a guess but it works fairly well
        // in practice
        //
        // note that we may guess wrongly in one direction only: i.e. we may
        // return true when there are no subdirectories but this is ok as the
        // caller will learn it soon enough when it calls GetFirst(wxDIR)
        // anyhow
        wxStructStat stBuf;
        if ( wxStat(M_DIR->GetName().c_str(), &stBuf) == 0 )
        {
            switch ( stBuf.st_nlink )
            {
                case 2:
                    // just "." and ".."
                    return false;

                case 0:
                case 1:
                    // weird filesystem, don't try to guess for it, use dumb
                    // method below
                    break;

                default:
                    // assume we have subdirs - may turn out to be wrong if we
                    // have other hard links to this directory but it's not
                    // that bad as explained above
                    return true;
            }
        }
    }

    // just try to find first directory
    wxString s;
    return GetFirst(&s, spec, wxDIR_DIRS | wxDIR_HIDDEN);
}
예제 #3
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;
        }
    }
}
예제 #4
0
void wxFileData::ReadData()
{
    if (IsDrive())
    {
        m_size = 0;
        return;
    }

#if defined(__WINDOWS__)
    // 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 // __WINDOWS__

    // OTHER PLATFORMS

    wxStructStat buff;

#if defined(__UNIX__) && !defined(__VMS)
    const bool hasStat = lstat( m_filePath.fn_str(), &buff ) == 0;
    if ( hasStat )
        m_type |= S_ISLNK(buff.st_mode) ? is_link : 0;
#else // no lstat()
    const bool hasStat = wxStat( m_filePath, &buff ) == 0;
#endif

    if ( hasStat )
    {
        m_type |= (buff.st_mode & S_IFDIR) != 0 ? is_dir : 0;
        m_type |= (buff.st_mode & wxS_IXUSR) != 0 ? is_exe : 0;

        m_size = buff.st_size;

        m_dateTime = buff.st_mtime;
    }

#if defined(__UNIX__)
    if ( hasStat )
    {
        m_permissions.Printf(wxT("%c%c%c%c%c%c%c%c%c"),
                             buff.st_mode & wxS_IRUSR ? wxT('r') : wxT('-'),
                             buff.st_mode & wxS_IWUSR ? wxT('w') : wxT('-'),
                             buff.st_mode & wxS_IXUSR ? wxT('x') : wxT('-'),
                             buff.st_mode & wxS_IRGRP ? wxT('r') : wxT('-'),
                             buff.st_mode & wxS_IWGRP ? wxT('w') : wxT('-'),
                             buff.st_mode & wxS_IXGRP ? wxT('x') : wxT('-'),
                             buff.st_mode & wxS_IROTH ? wxT('r') : wxT('-'),
                             buff.st_mode & wxS_IWOTH ? wxT('w') : wxT('-'),
                             buff.st_mode & wxS_IXOTH ? wxT('x') : wxT('-'));
    }
#elif defined(__WIN32__)
    DWORD attribs = ::GetFileAttributes(m_filePath.c_str());
    if (attribs != (DWORD)-1)
    {
        m_permissions.Printf(wxT("%c%c%c%c"),
                             attribs & FILE_ATTRIBUTE_ARCHIVE  ? wxT('A') : wxT(' '),
                             attribs & FILE_ATTRIBUTE_READONLY ? wxT('R') : wxT(' '),
                             attribs & FILE_ATTRIBUTE_HIDDEN   ? wxT('H') : wxT(' '),
                             attribs & FILE_ATTRIBUTE_SYSTEM   ? wxT('S') : wxT(' '));
    }
#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;
        }
    }
}
예제 #5
0
bool wxSingleInstanceCheckerImpl::Create(const wxString& name)
{
    m_nameLock = name;

    switch ( CreateLockFile() )
    {
        case LOCK_EXISTS:
            // there is a lock file, check below if it is still valid
            break;

        case LOCK_CREATED:
            // nothing more to do
            return true;

        case LOCK_ERROR:
            // oops...
            return false;
    }

    // Check if the file is owned by current user and has 0600 permissions.
    // If it doesn't, it's a fake file, possibly meant as a DoS attack, and
    // so we refuse to touch it:
    wxStructStat stats;
    if ( wxStat(name, &stats) != 0 )
    {
        wxLogSysError(_("Failed to inspect the lock file '%s'"), name.c_str());
        return false;
    }
    if ( stats.st_uid != getuid() )
    {
        wxLogError(_("Lock file '%s' has incorrect owner."), name.c_str());
        return false;
    }
    if ( stats.st_mode != (S_IFREG | S_IRUSR | S_IWUSR) )
    {
        wxLogError(_("Lock file '%s' has incorrect permissions."), name.c_str());
        return false;
    }

    // try to open the file for reading and get the PID of the process
    // which has it
    wxFile file(name, wxFile::read);
    if ( !file.IsOpened() )
    {
        // well, this is really weird - file doesn't exist and we can't
        // create it
        //
        // normally, this just means that we don't have write access to
        // the directory where we try to create it, so return failure,
        // even it might also be a rare case of a race condition when
        // another process managed to open and lock the file and terminate
        // (erasing it) before we got here, but this should happen so
        // rarely in practice that we don't care
        wxLogError(_("Failed to access lock file."));

        return false;
    }

    char buf[256];
    ssize_t count = file.Read(buf, WXSIZEOF(buf));
    if ( count == wxInvalidOffset )
    {
        wxLogError(_("Failed to read PID from lock file."));
    }
    else
    {
        if ( sscanf(buf, "%d", (int *)&m_pidLocker) == 1 )
        {
            if ( kill(m_pidLocker, 0) != 0 )
            {
                if ( unlink(name.fn_str()) != 0 )
                {
                    wxLogError(_("Failed to remove stale lock file '%s'."),
                               name.c_str());

                    // return true in this case for now...
                }
                else
                {
                    wxLogMessage(_("Deleted stale lock file '%s'."),
                                 name.c_str());

                    // retry now
                    (void)CreateLockFile();
                }
            }
            //else: the other process is running
        }
        else
        {
            wxLogWarning(_("Invalid lock file '%s'."), name.c_str());
        }
    }

    // return true if we could get the PID of the process owning the lock file
    // (whether it is still running or not), FALSE otherwise as it is
    // unexpected
    return m_pidLocker != 0;
}
예제 #6
0
bool CLocalListView::DisplayDir(wxString dirname)
{
	wxString focused;
	std::list<wxString> selectedNames;
	if (m_dir != dirname)
	{
		// Clear selection
		int item = -1;
		while (true)
		{
			item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
			if (item == -1)
				break;
			SetItemState(item, 0, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
		}
		focused = _T("..");

		if (GetItemCount())
			EnsureVisible(0);
		m_dir = dirname;
	}
	else
	{
		// Remember which items were selected
		selectedNames = RememberSelectedItems(focused);
	}

	const int oldItemCount = m_indexMapping.size();

	m_fileData.clear();
	m_indexMapping.clear();

	m_hasParent = CState::LocalDirHasParent(dirname);

	if (m_hasParent)
	{
		t_fileData data;
		data.dir = true;
		data.icon = -2;
		data.name = _T("..");
		data.size = -1;
		data.hasTime = 0;
		m_fileData.push_back(data);
		m_indexMapping.push_back(0);
	}

#ifdef __WXMSW__
	if (dirname == _T("\\"))
	{
		DisplayDrives();
	}
	else if (dirname.Left(2) == _T("\\\\"))
	{
		int pos = dirname.Mid(2).Find('\\');
		if (pos != -1 && pos + 3 != (int)dirname.Len())
			goto regular_dir;

		// UNC path without shares
		DisplayShares(dirname);
	}
	else
#endif
	{
#ifdef __WXMSW__
regular_dir:
#endif
		CFilterDialog filter;

		wxDir dir(dirname);
		if (!dir.IsOpened())
		{
			SetItemCount(1);
			return false;
		}
		wxString file;
		bool found = dir.GetFirst(&file);
		int num = m_fileData.size();
		while (found)
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				found = dir.GetNext(&file);
				continue;
			}
			t_fileData data;

			data.dir = wxFileName::DirExists(dirname + file);
			data.icon = -2;
			data.name = file;

			wxStructStat buf;
			int result;
			result = wxStat(dirname + file, &buf);

			if (!result)
			{
				data.hasTime = true;
				data.lastModified = wxDateTime(buf.st_mtime);
			}
			else
				data.hasTime = false;

			if (data.dir)
				data.size = -1;
			else
				data.size = result ? -1 : buf.st_size;

			m_fileData.push_back(data);
			if (!filter.FilenameFiltered(data.name, data.dir, data.size, true))
				m_indexMapping.push_back(num);
			num++;

			found = dir.GetNext(&file);
		}
	}

	if (m_dropTarget != -1)
	{
		t_fileData* data = GetData(m_dropTarget);
		if (!data || !data->dir)
		{
			SetItemState(m_dropTarget, 0, wxLIST_STATE_DROPHILITED);
			m_dropTarget = -1;
		}
	}

	const int count = m_indexMapping.size();
	if (oldItemCount != count)
		SetItemCount(count);

	SortList();

	ReselectItems(selectedNames, focused);

	Refresh();

	return true;
}
예제 #7
0
void CLocalListView::RefreshFile(const wxString& file)
{
	if (!wxFileName::FileExists(m_dir + file))
		return;

	t_fileData data;

	data.dir = wxFileName::DirExists(m_dir + file);
	data.icon = -2;
	data.name = file;

	wxStructStat buf;
	int result = wxStat(m_dir + file, &buf);

	if (!result)
	{
		data.hasTime = true;
		data.lastModified = wxDateTime(buf.st_mtime);
	}
	else
		data.hasTime = false;

	if (data.dir)
		data.size = -1;
	else
		data.size = result ? -1 : buf.st_size;

	// Look if file data already exists
	for (std::vector<t_fileData>::iterator iter = m_fileData.begin(); iter != m_fileData.end(); iter++)
	{
		const t_fileData& oldData = *iter;
		if (oldData.name != file)
			continue;

		// It exists, update entry
		data.fileType = oldData.fileType;

		*iter = data;
		if (m_sortColumn)
			SortList();
		Refresh(false);
		return;
	}

	// Insert new entry
	int index = m_fileData.size();
	m_fileData.push_back(data);

	// Find correct position in index mapping
	std::vector<unsigned int>::iterator start = m_indexMapping.begin();
	if (m_hasParent)
		start++;
	CLocalListViewSortObject compare = GetComparisonObject();
	std::vector<unsigned int>::iterator insertPos = std::lower_bound(start, m_indexMapping.end(), index, compare);
	compare.Destroy();

	const int item = insertPos - m_indexMapping.begin();
	m_indexMapping.insert(insertPos, index);
	SetItemCount(m_indexMapping.size());

	// Move selections
	int prevState = 0;
	for (unsigned int i = item; i < m_indexMapping.size(); i++)
	{
		int state = GetItemState(i, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
		if (state != prevState)
		{
			SetItemState(i, prevState, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED);
			prevState = state;
		}
	}

	Refresh(false);
}
예제 #8
0
// Copy files
bool
wxCopyFile (const wxString& file1, const wxString& file2, bool overwrite)
{
#if defined(__WIN32__)
    // CopyFile() copies file attributes and modification time too, so use it
    // instead of our code if available
    //
    // NB: 3rd parameter is bFailIfExists i.e. the inverse of overwrite
    if ( !::CopyFile(file1.t_str(), file2.t_str(), !overwrite) )
    {
        wxLogSysError(_("Failed to copy the file '%s' to '%s'"),
                      file1.c_str(), file2.c_str());

        return false;
    }
#elif wxUSE_FILE // !Win32

    wxStructStat fbuf;
    // get permissions of file1
    if ( wxStat( file1, &fbuf) != 0 )
    {
        // the file probably doesn't exist or we haven't the rights to read
        // from it anyhow
        wxLogSysError(_("Impossible to get permissions for file '%s'"),
                      file1.c_str());
        return false;
    }

    // open file1 for reading
    wxFile fileIn(file1, wxFile::read);
    if ( !fileIn.IsOpened() )
        return false;

    // remove file2, if it exists. This is needed for creating
    // file2 with the correct permissions in the next step
    if ( wxFileExists(file2)  && (!overwrite || !wxRemoveFile(file2)))
    {
        wxLogSysError(_("Impossible to overwrite the file '%s'"),
                      file2.c_str());
        return false;
    }

    if ( !wxDoCopyFile(fileIn, fbuf, file2, overwrite) )
    {
        wxLogError(_("Error copying the file '%s' to '%s'."), file1, file2);
        return false;
    }

#if defined(__WXMAC__)
    // copy the resource fork of the file too if it's present
    wxString pathRsrcOut;
    wxFile fileRsrcIn;

    {
        // suppress error messages from this block as resource forks don't have
        // to exist
        wxLogNull noLog;

        // it's not enough to check for file existence: it always does on HFS
        // but is empty for files without resources
        if ( fileRsrcIn.Open(file1 + wxT("/..namedfork/rsrc")) &&
                fileRsrcIn.Length() > 0 )
        {
            // we must be using HFS or another filesystem with resource fork
            // support, suppose that destination file system also is HFS[-like]
            pathRsrcOut = file2 + wxT("/..namedfork/rsrc");
        }
        else // check if we have resource fork in separate file (non-HFS case)
        {
            wxFileName fnRsrc(file1);
            fnRsrc.SetName(wxT("._") + fnRsrc.GetName());

            fileRsrcIn.Close();
            if ( fileRsrcIn.Open( fnRsrc.GetFullPath() ) )
            {
                fnRsrc = file2;
                fnRsrc.SetName(wxT("._") + fnRsrc.GetName());

                pathRsrcOut = fnRsrc.GetFullPath();
            }
        }
    }

    if ( !pathRsrcOut.empty() )
    {
        if ( !wxDoCopyFile(fileRsrcIn, fbuf, pathRsrcOut, overwrite) )
            return false;
    }
#endif // wxMac

    if ( chmod(file2.fn_str(), fbuf.st_mode) != 0 )
    {
        wxLogSysError(_("Impossible to set permissions for the file '%s'"),
                      file2.c_str());
        return false;
    }

#else // !Win32 && ! wxUSE_FILE

    // impossible to simulate with wxWidgets API
    wxUnusedVar(file1);
    wxUnusedVar(file2);
    wxUnusedVar(overwrite);
    return false;

#endif // __WINDOWS__ && __WIN32__

    return true;
}
예제 #9
0
// -------------------------------------------------------------------------------- //
wxFileOffset guGetFileSize( const wxString &FileName )
{
    wxStructStat St;
    wxStat( FileName, &St );
    return St.st_size;
}
예제 #10
0
int CControlSocket::CheckOverwriteFile()
{
	if (!m_pCurOpData)
	{
		LogMessage(__TFILE__, __LINE__, this, Debug_Info, _T("Empty m_pCurOpData"));
		ResetOperation(FZ_REPLY_INTERNALERROR);
		return FZ_REPLY_ERROR;
	}

	CFileTransferOpData *pData = static_cast<CFileTransferOpData *>(m_pCurOpData);

	if (pData->download)
	{
		if (!wxFile::Exists(pData->localFile))
			return FZ_REPLY_OK;
	}

	CDirentry entry;
	bool dirDidExist;
	bool matchedCase;
	CDirectoryCache cache;
	CServerPath remotePath;
	if (pData->tryAbsolutePath || m_CurrentPath.IsEmpty())
		remotePath = pData->remotePath;
	else
		remotePath = m_CurrentPath;
	bool found = cache.LookupFile(entry, *m_pCurrentServer, remotePath, pData->remoteFile, dirDidExist, matchedCase);

	// Ignore entries with wrong case
	if (found && !matchedCase)
		found = false;

	if (!pData->download)
	{
		if (!found && pData->remoteFileSize == -1 && !pData->fileTime.IsValid())
			return FZ_REPLY_OK;
	}

	CFileExistsNotification *pNotification = new CFileExistsNotification;

	pNotification->download = pData->download;
	pNotification->localFile = pData->localFile;
	pNotification->remoteFile = pData->remoteFile;
	pNotification->remotePath = pData->remotePath;
	pNotification->localSize = pData->localFileSize;
	pNotification->remoteSize = pData->remoteFileSize;
	pNotification->ascii = !pData->transferSettings.binary;

	wxStructStat buf;
	int result;
	result = wxStat(pData->localFile, &buf);
	if (!result)
	{
		pNotification->localTime = wxDateTime(buf.st_mtime);
		if (!pNotification->localTime.IsValid())
			pNotification->localTime = wxDateTime(buf.st_ctime);
	}

	if (pData->fileTime.IsValid())
		pNotification->remoteTime = pData->fileTime;

	if (found)
	{
		if (!pData->fileTime.IsValid())
		{
			if (entry.hasDate)
			{
				pNotification->remoteTime = entry.time;
				pData->fileTime = entry.time;
			}
		}
	}

	pNotification->requestNumber = m_pEngine->GetNextAsyncRequestNumber();
	pData->waitForAsyncRequest = true;

	m_pEngine->AddNotification(pNotification);

	return FZ_REPLY_WOULDBLOCK;
}
예제 #11
0
enum CLocalFileSystem::local_fileType CLocalFileSystem::GetFileInfo(const wxString& path, bool &isLink, wxLongLong* size, wxDateTime* modificationTime, int *mode)
{
	if (path.Last() == wxFileName::GetPathSeparator() && path != wxFileName::GetPathSeparator())
	{
		wxString tmp = path;
		tmp.RemoveLast();
		return GetFileInfo(tmp, isLink, size, modificationTime, mode);
	}

#ifdef __WXMSW__
	isLink = false;

	WIN32_FILE_ATTRIBUTE_DATA attributes;
	BOOL result = GetFileAttributesEx(path, GetFileExInfoStandard, &attributes);
	if (!result)
	{
		if (size)
			*size = -1;
		if (mode)
			*mode = 0;
		return unknown;
	}

	if (modificationTime)
		ConvertFileTimeToWxDateTime(*modificationTime, attributes.ftLastWriteTime);

	if (mode)
		*mode = (int)attributes.dwFileAttributes;

	if (attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
	{
		if (size)
			*size = -1;
		return dir;
	}

	if (size)
		*size = wxLongLong(attributes.nFileSizeHigh, attributes.nFileSizeLow);

	return file;
#else
	wxStructStat buf;
	int result = wxLstat(path, &buf);
	if (result)
	{
		isLink = false;
		if (size)
			*size = -1;
		if (mode)
			*mode = -1;
		return unknown;
	}

#ifdef S_ISLNK
	if (S_ISLNK(buf.st_mode))
	{
		isLink = true;
		int result = wxStat(path, &buf);
		if (result)
		{
			if (size)
				*size = -1;
			if (mode)
				*mode = -1;
			return unknown;
		}
	}
	else
#endif
		isLink = false;

	if (modificationTime)
		modificationTime->Set(buf.st_mtime);

	if (mode)
		*mode = buf.st_mode & 0x777;

	if (S_ISDIR(buf.st_mode))
	{
		if (size)
			*size = -1;
		return dir;
	}

	if (size)
		*size = buf.st_size;

	return file;
#endif
}
예제 #12
0
void CLocalTreeView::Refresh()
{
	wxLogNull nullLog;

	const wxString separator = wxFileName::GetPathSeparator();

	std::list<t_dir> dirsToCheck;

#ifdef __WXMSW__
	int prevErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS);

	wxTreeItemIdValue tmp;
	wxTreeItemId child = GetFirstChild(m_drives, tmp);
	while (child)
	{
		if (IsExpanded(child))
		{
			wxString drive = GetItemText(child);
			int pos = drive.Find(_T(" "));
			if (pos != -1)
				drive = drive.Left(pos);

			t_dir dir;
			dir.dir = drive + separator;
			dir.item = child;
			dirsToCheck.push_back(dir);
		}

		child = GetNextSibling(child);
	}
#else
	t_dir dir;
	dir.dir = separator;
	dir.item = GetRootItem();
	dirsToCheck.push_back(dir);
#endif

	CFilterDialog filter;

	while (!dirsToCheck.empty())
	{
		t_dir dir = dirsToCheck.front();
		dirsToCheck.pop_front();

		wxDir find(dir.dir);
		if (!find.IsOpened())
		{
			// Dir does exist (listed in parent) but may not be accessible.
			// Recurse into children anyhow, they might be accessible again.
			wxTreeItemIdValue value;
			wxTreeItemId child = GetFirstChild(dir.item, value);
			while (child)
			{
				t_dir subdir;
				subdir.dir = dir.dir + GetItemText(child) + separator;
				subdir.item = child;
				dirsToCheck.push_back(subdir);

				child = GetNextSibling(child);
			}
			continue;
		}

		wxString file;
		bool found = find.GetFirst(&file, _T(""), wxDIR_DIRS | wxDIR_HIDDEN);
		std::list<wxString> dirs;
		while (found)
		{
			if (file == _T(""))
			{
				wxGetApp().DisplayEncodingWarning();
				found = find.GetNext(&file);
				continue;
			}
			wxFileName fn(dir.dir + file);
			const bool isDir = fn.DirExists();

			wxLongLong size;

			wxStructStat buf;
			int result = wxStat(fn.GetFullPath(), &buf);
			if (!isDir && !result)
				size = buf.st_size;
			else
				size = -1;

			int attributes;
#ifdef __WXMSW__
			DWORD tmp = GetFileAttributes(fn.GetFullPath());
			if (tmp == INVALID_FILE_ATTRIBUTES)
				attributes = 0;
			else
				attributes = tmp;
#else
			if (!result)
				attributes = buf.st_mode & 0x777;
			else
				attributes = -1;
#endif //__WXMSW__

			if (!filter.FilenameFiltered(file, isDir, size , true, attributes))
				dirs.push_back(file);
			found = find.GetNext(&file);
		}
		dirs.sort(sortfunc);

		bool inserted = false;

		wxTreeItemId child = GetLastChild(dir.item);
		std::list<wxString>::reverse_iterator iter = dirs.rbegin();
		while (child && iter != dirs.rend())
		{
#ifdef __WXMSW__
			int cmp = GetItemText(child).CmpNoCase(*iter);
#else
			int cmp = GetItemText(child).Cmp(*iter);
#endif
			if (!cmp)
			{
				if (!IsExpanded(child))
				{
					wxTreeItemId subchild = GetLastChild(child);
					if (subchild && GetItemText(subchild) == _T(""))
					{
						if (!HasSubdir(dir.dir + *iter + separator))
							Delete(subchild);
					}
					else if (!subchild)
					{
						if (HasSubdir(dir.dir + *iter + separator))
							AppendItem(child, _T(""));
					}
					else
					{
						t_dir subdir;
						subdir.dir = dir.dir + *iter + separator;
						subdir.item = child;
						dirsToCheck.push_front(subdir);
					}
				}
				else
				{
					t_dir subdir;
					subdir.dir = dir.dir + *iter + separator;
					subdir.item = child;
					dirsToCheck.push_front(subdir);
				}
				child = GetPrevSibling(child);
				iter++;
			}
			else if (cmp > 0)
			{
				wxTreeItemId sel = GetSelection();
				while (sel && sel != child)
					sel = GetItemParent(sel);
				wxTreeItemId prev = GetPrevSibling(child);
				if (!sel)
					Delete(child);
				child = prev;
			}
			else if (cmp < 0)
			{
				wxString fullname = dir.dir + *iter + separator;
				wxTreeItemId newItem = AppendItem(dir.item, *iter, GetIconIndex(::dir, fullname), GetIconIndex(opened_dir, fullname));
				if (HasSubdir(fullname))
					AppendItem(newItem, _T(""));
				iter++;
				inserted = true;
			}
		}
		while (child)
		{
			wxTreeItemId sel = GetSelection();
			while (sel && sel != child)
				sel = GetItemParent(sel);
			wxTreeItemId prev = GetPrevSibling(child);
			if (!sel)
				Delete(child);
			child = prev;
		}
		while (iter != dirs.rend())
		{
			wxString fullname = dir.dir + *iter + separator;
			wxTreeItemId newItem = AppendItem(dir.item, *iter, GetIconIndex(::dir, fullname), GetIconIndex(opened_dir, fullname));
			if (HasSubdir(fullname))
				AppendItem(newItem, _T(""));
			iter++;
			inserted = true;
		}
		if (inserted)
			SortChildren(dir.item);
	}

#ifdef __WXMSW__
	SetErrorMode(prevErrorMode);
#endif
}
예제 #13
0
void CLocalTreeView::DisplayDir(wxTreeItemId parent, const wxString& dirname, const wxString& knownSubdir /*=_T("")*/)
{
	wxDir dir;

	{
		wxLogNull log;
		if (!dir.Open(dirname))
		{
			if (knownSubdir != _T(""))
			{
				wxTreeItemId item = GetSubdir(parent, knownSubdir);
				if (item != wxTreeItemId())
					return;

				const wxString fullName = dirname + knownSubdir;
				item = AppendItem(parent, knownSubdir, GetIconIndex(::dir, fullName), GetIconIndex(opened_dir, fullName));
				if (HasSubdir(fullName))
					AppendItem(item, _T(""));
			}
			else
			{
				m_setSelection = true;
				DeleteChildren(parent);
				m_setSelection = false;
			}
			return;
		}
	}

	wxASSERT(parent);
	m_setSelection = true;
	DeleteChildren(parent);
	m_setSelection = false;

	wxString file;

	CFilterDialog filter;

	bool matchedKnown = false;

	for (bool found = dir.GetFirst(&file, _T(""), wxDIR_DIRS | wxDIR_HIDDEN); found; found = dir.GetNext(&file))
	{
		if (file == _T(""))
		{
			wxGetApp().DisplayEncodingWarning();
			continue;
		}

		wxString fullName = dirname + file;
#ifdef __WXMSW__
		if (file.CmpNoCase(knownSubdir))
#else
		if (file != knownSubdir)
#endif
		{
			wxFileName fn(fullName);
			const bool isDir = fn.DirExists();

			wxLongLong size;

			const wxString& fullName = fn.GetFullPath();
			wxStructStat buf;
			int result = wxStat(fullName, &buf);
			if (!isDir && !result)
				size = buf.st_size;
			else
				size = -1;

			int attributes;
#ifdef __WXMSW__
			DWORD tmp = GetFileAttributes(fullName);
			if (tmp == INVALID_FILE_ATTRIBUTES)
				attributes = 0;
			else
				attributes = tmp;
#else
			if (!result)
				attributes = buf.st_mode & 0x777;
			else
				attributes = -1;
#endif //__WXMSW__

			if (filter.FilenameFiltered(file, isDir, size, true, attributes))
				continue;
		}
		else
			matchedKnown = true;

		wxTreeItemId item = AppendItem(parent, file, GetIconIndex(::dir, fullName), GetIconIndex(opened_dir, fullName));
		if (HasSubdir(fullName))
			AppendItem(item, _T(""));
	}

	if (!matchedKnown && knownSubdir != _T(""))
	{
		const wxString fullName = dirname + knownSubdir;
		wxTreeItemId item = AppendItem(parent, knownSubdir, GetIconIndex(::dir, fullName), GetIconIndex(opened_dir, fullName));
		if (HasSubdir(fullName))
			AppendItem(item, _T(""));
	}

	SortChildren(parent);
}