bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
{
#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
    // the case to "char *" is needed for AIX 4.3
    wxStatfs_t fs;
    if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
    {
        wxLogSysError( wxT("Failed to get file system statistics") );

        return false;
    }

    // under Solaris we also have to use f_frsize field instead of f_bsize
    // which is in general a multiple of f_frsize
#ifdef HAVE_STATVFS
    wxLongLong blockSize = fs.f_frsize;
#else // HAVE_STATFS
    wxLongLong blockSize = fs.f_bsize;
#endif // HAVE_STATVFS/HAVE_STATFS

    if ( pTotal )
    {
        *pTotal = wxLongLong(fs.f_blocks) * blockSize;
    }

    if ( pFree )
    {
        *pFree = wxLongLong(fs.f_bavail) * blockSize;
    }

    return true;
#else // !HAVE_STATFS && !HAVE_STATVFS
    return false;
#endif // HAVE_STATFS
}
Example #2
0
wxString wxDownloadThread::GetRemainingTime() const
{
    wxASSERT(IsDownloading());
    wxLongLong sec = GetElapsedMSec()/1000;
    if (sec <= 0)
        return wxT("not available");        // avoid division by zero

    // remaining time is the number of bytes we still need to download
    // divided by our download speed...
    wxLongLong nBytesPerSec = wxLongLong(GetCurrDownloadedBytes()) / sec;
    if (nBytesPerSec <= 0)
        return wxT("not available");        // avoid division by zero

    long remsec = (wxLongLong(m_nFinalSize-GetCurrDownloadedBytes())/nBytesPerSec).ToLong();
    if (remsec < 0)
        return wxT("not available");

    if (remsec < 60)
        return wxString::Format(wxT("%li sec"), remsec);
    else if (remsec < 60*60)
        return wxString::Format(wxT("%li min, %li sec"), remsec/60, remsec%60);
    else if (remsec < 60*60*24)
        return wxString::Format(wxT("%li hours, %li min, %li sec"),
                    remsec/3600, (remsec/60)%60, (remsec/3600)%60);
    else
        return wxT("not available");
}
Example #3
0
void CUpdateWizard::SetTransferStatus(const CTransferStatus* pStatus)
{
	if (!pStatus)
	{
		if (m_statusTimer.IsRunning())
			m_statusTimer.Stop();
		return;
	}


	wxTimeSpan elapsed = wxDateTime::Now().Subtract(pStatus->started);
	int elapsedSeconds = elapsed.GetSeconds().GetLo(); // Assume GetHi is always 0

	wxString text;
	if (elapsedSeconds)
	{
		wxFileOffset rate = (pStatus->currentOffset - pStatus->startOffset) / elapsedSeconds;

		CSizeFormat::_format format = static_cast<CSizeFormat::_format>(COptions::Get()->GetOptionVal(OPTION_SIZE_FORMAT));
		if (format == CSizeFormat::bytes)
			format = CSizeFormat::iec;
		const wxString ratestr = CSizeFormat::Format(rate, true,
													 format,
													 COptions::Get()->GetOptionVal(OPTION_SIZE_USETHOUSANDSEP) != 0,
													 COptions::Get()->GetOptionVal(OPTION_SIZE_DECIMALPLACES));

		text.Printf(_("%s bytes (%s/s)"), wxLongLong(pStatus->currentOffset).ToString().c_str(), ratestr.c_str());

		if (pStatus->totalSize > 0 && rate > 0)
		{
			int left = ((pStatus->totalSize - pStatus->startOffset) / rate) - elapsedSeconds;
			if (left < 0)
				left = 0;
			wxTimeSpan timeLeft(0, 0, left);
			text += timeLeft.Format(_(", %H:%M:%S left"));
		}
		else
		{
			text += _(", --:--:-- left");
		}
	}
	else
		text.Format(_("%s bytes"), wxLongLong(pStatus->currentOffset).ToString().c_str());

	XRCCTRL(*this, "ID_DOWNLOADPROGRESSTEXT", wxStaticText)->SetLabel(text);
	m_pages[2]->GetSizer()->Layout();

	if (pStatus->totalSize > 0)
	{
		int percent = (pStatus->currentOffset * 100) / pStatus->totalSize;
		if (percent > 100)
			percent = 100;
		XRCCTRL(*this, "ID_DOWNLOADPROGRESS", wxGauge)->SetValue(percent);
	}

	if (!m_statusTimer.IsRunning())
		m_statusTimer.Start(100);
}
void WXMSearchReplaceDialog::UpdateSearchInSelection(bool check)
{
	WxEditFrom->Enable(check);
	WxEditTo->Enable(check);

	if (check && g_active_wxmedit!=nullptr)
	{
		WxEditFrom->SetValue(wxLongLong(g_active_wxmedit->GetSelectionBeginPos()).ToString());
		WxEditTo->SetValue(wxLongLong(g_active_wxmedit->GetSelectionEndPos()).ToString());
	}
}
Example #5
0
void AnimationSetItem::Init(int start, int end, float rate,int idx, SkeletonMeshEditor* pEditor)
{
    m_staticText1->SetLabel(wxLongLong(start).ToString());
    m_staticText2->SetLabel(wxLongLong(end).ToString());
    m_staticText3->SetLabel(wxString::FromDouble(rate));
    m_Index = idx;
    m_pSkeletonMeshEditor = pEditor;    
    
    m_pSkeletonMeshEditor->FocusAnimation(m_Index);
    FocusThis(true);
}
Example #6
0
void MadReplaceDialog::UpdateSearchInSelection(bool check)
{
    WxEditFrom->Enable(check);
    WxEditTo->Enable(check);

    extern MadEdit *g_ActiveMadEdit;
    if(check && g_ActiveMadEdit!=NULL)
    {
        WxEditFrom->SetValue(wxLongLong(g_ActiveMadEdit->GetSelectionBeginPos()).ToString());
        WxEditTo->SetValue(wxLongLong(g_ActiveMadEdit->GetSelectionEndPos()).ToString());
    }
}
Example #7
0
// Declared const due to design error in wxWidgets.
// Won't be fixed since a fix would break backwards compatibility
// Both functions use a const_cast<CLocalListView *>(this) and modify
// the instance.
wxString CLocalListView::OnGetItemText(long item, long column) const
{
	CLocalListView *pThis = const_cast<CLocalListView *>(this);
	t_fileData *data = pThis->GetData(item);
	if (!data)
		return _T("");

	if (!column)
		return data->name;
	else if (column == 1)
	{
		if (data->size < 0)
			return _T("");
		else
			return wxLongLong(data->size).ToString();
	}
	else if (column == 2)
	{
		if (!item && m_hasParent)
			return _T("");

		if (data->fileType == _T(""))
			data->fileType = pThis->GetType(data->name, data->dir);

		return data->fileType;
	}
	else if (column == 3)
	{
		if (!data->hasTime)
			return _T("");

		return data->lastModified.Format(_T("%c"));
	}
	return _T("");
}
Example #8
0
wxString wxFileData::GetHint() const
{
    wxString s = m_filePath;
    s += wxT("  ");

    if (IsDir())
        s += _("<DIR>");
    else if (IsLink())
        s += _("<LINK>");
    else if (IsDrive())
        s += _("<DRIVE>");
    else // plain file
        s += wxString::Format(wxPLURAL("%ld byte", "%ld bytes", m_size),
                              wxLongLong(m_size).ToString().c_str());

    s += wxT(' ');

    if ( !IsDrive() )
    {
        s << GetModificationTime()
          << wxT("  ")
          << m_permissions;
    }

    return s;
}
Example #9
0
wxString wxFileData::GetEntry( fileListFieldType num ) const
{
    wxString s;
    switch ( num )
    {
        case FileList_Name:
            s = m_fileName;
            break;

        case FileList_Size:
            if (!IsDir() && !IsLink() && !IsDrive())
                s = wxLongLong(m_size).ToString();
            break;

        case FileList_Type:
            s = GetFileType();
            break;

        case FileList_Time:
            if (!IsDrive())
                s = GetModificationTime();
            break;

#if defined(__UNIX__) || defined(__WIN32__)
        case FileList_Perm:
            s = m_permissions;
            break;
#endif // defined(__UNIX__) || defined(__WIN32__)

        default:
            wxFAIL_MSG( wxT("unexpected field in wxFileData::GetEntry()") );
    }

    return s;
}
Example #10
0
void PHPEntityVariable::Store(wxSQLite3Database& db)
{
    // we keep only the function arguments in the databse and globals
    if(IsFunctionArg() || IsMember()) {
        try {
            wxSQLite3Statement statement =
                db.PrepareStatement("INSERT OR REPLACE INTO VARIABLES_TABLE VALUES (NULL, "
                                    ":SCOPE_ID, :FUNCTION_ID, :NAME, :FULLNAME, :SCOPE, :TYPEHINT, "
                                    ":FLAGS, :DOC_COMMENT, :LINE_NUMBER, :FILE_NAME)");
            statement.Bind(statement.GetParamIndex(":SCOPE_ID"), IsMember() ? Parent()->GetDbId() : wxLongLong(-1));
            statement.Bind(statement.GetParamIndex(":FUNCTION_ID"),
                           IsFunctionArg() ? Parent()->GetDbId() : wxLongLong(-1));
            statement.Bind(statement.GetParamIndex(":NAME"), GetShortName());
            statement.Bind(statement.GetParamIndex(":FULLNAME"), GetFullName());
            statement.Bind(statement.GetParamIndex(":SCOPE"), GetScope());
            statement.Bind(statement.GetParamIndex(":TYPEHINT"), GetTypeHint());
            statement.Bind(statement.GetParamIndex(":FLAGS"), (int)GetFlags());
            statement.Bind(statement.GetParamIndex(":DOC_COMMENT"), GetDocComment());
            statement.Bind(statement.GetParamIndex(":LINE_NUMBER"), GetLine());
            statement.Bind(statement.GetParamIndex(":FILE_NAME"), GetFilename().GetFullPath());
            statement.ExecuteUpdate();
            SetDbId(db.GetLastRowId());

        } catch(wxSQLite3Exception& exc) {
            wxUnusedVar(exc);
        }
    }
}
Example #11
0
bool wxTarOutputStream::SetHeaderNumber(int id, wxTarNumber n)
{
    if (m_hdr->SetOctal(id, n)) {
        return true;
    } else {
        SetExtendedHeader(m_hdr->Name(id), wxLongLong(n).ToString());
        return false;
    }
}
Example #12
0
void wxStopWatch::Start(long t0)
{
    // Calling Start() makes the stop watch run however many times it was
    // paused before.
    m_pauseCount = 0;

    DoStart();

    m_t0 -= (wxLongLong(t0)*GetClockFreq())/MILLISECONDS_PER_SECOND;
}
Example #13
0
NS_IMETHODIMP ProgressListenerAdaptor::OnProgressChange64(
                         nsIWebProgress* web_progress,
                         nsIRequest* request,
                         PRInt64 cur_self_progress,
                         PRInt64 max_self_progress,
                         PRInt64 cur_total_progress,
                         PRInt64 max_total_progress)
{
    if (m_progress)
    {
        m_progress->OnProgressChange(wxLongLong(cur_self_progress),
                                     wxLongLong(max_self_progress));
                                     
        if (m_progress->IsCancelled())
            request->Cancel(0x804b0002 /*NS_BINDING_ABORTED*/);
    }
    
    return NS_OK;
}
Example #14
0
bool wxGetDiskSpace(const wxString& WXUNUSED_IN_WINCE(path),
                    wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pTotal),
                    wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pFree))
{
#ifdef __WXWINCE__
    // TODO-CE
    return false;
#else
    if ( path.empty() )
        return false;

    ULARGE_INTEGER bytesFree, bytesTotal;

    // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
    if ( !::GetDiskFreeSpaceEx(path.t_str(),
                               &bytesFree,
                               &bytesTotal,
                               NULL) )
    {
        wxLogLastError(wxT("GetDiskFreeSpaceEx"));

        return false;
    }

    // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
    // two 32 bit fields which may be or may be not named - try to make it
    // compile in all cases
#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
    #define UL(ul) ul.u
#else // anon union
    #define UL(ul) ul
#endif
    if ( pTotal )
    {
#if wxUSE_LONGLONG
        *pTotal = wxDiskspaceSize_t(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
#else
        *pTotal = wxDiskspaceSize_t(UL(bytesTotal).LowPart);
#endif
    }

    if ( pFree )
    {
#if wxUSE_LONGLONG
        *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
#else
        *pFree = wxDiskspaceSize_t(UL(bytesFree).LowPart);
#endif
    }

    return true;
#endif
    // __WXWINCE__
}
void COptionsPageSizeFormatting::UpdateExamples()
{
	XRCCTRL(*this, "ID_EXAMPLE1", wxStaticText)->SetLabel(FormatSize(12));
	XRCCTRL(*this, "ID_EXAMPLE2", wxStaticText)->SetLabel(FormatSize(100));
	XRCCTRL(*this, "ID_EXAMPLE3", wxStaticText)->SetLabel(FormatSize(1234));
	XRCCTRL(*this, "ID_EXAMPLE4", wxStaticText)->SetLabel(FormatSize(1058817));
	XRCCTRL(*this, "ID_EXAMPLE5", wxStaticText)->SetLabel(FormatSize(123456789));
	XRCCTRL(*this, "ID_EXAMPLE6", wxStaticText)->SetLabel(FormatSize(wxLongLong(0x39E9, 0x4F995A72)));

	GetSizer()->Layout();
}
Example #16
0
wxString wxDownloadThread::GetDownloadSpeed() const
{
    wxASSERT(IsDownloading());
    wxLongLong msec = GetElapsedMSec();
    if (msec <= 0)
        return wxT("0 KB/s");       // avoid division by zero

    wxLongLong nBytesPerMilliSec = wxLongLong(GetCurrDownloadedBytes()) / msec;

    // we don't like bytes per millisecond as measure unit !
    long nKBPerSec = (nBytesPerMilliSec * 1000/1024).ToLong();          // our conversion factor
    return wxString::Format(wxT("%li KB/s"), nKBPerSec);
}
Example #17
0
void DataStreamTestCase::LongLongRW()
{
    TestMultiRW<wxLongLong>::ValueArray ValuesLL;
    TestMultiRW<wxULongLong>::ValueArray ValuesULL;

    ValuesLL.push_back(wxLongLong(0l));
    ValuesLL.push_back(wxLongLong(1l));
    ValuesLL.push_back(wxLongLong(-1l));
    ValuesLL.push_back(wxLongLong(0x12345678l));
    ValuesLL.push_back(wxLongLong(0x12345678l, 0xabcdef01l));

    ValuesULL.push_back(wxULongLong(0l));
    ValuesULL.push_back(wxULongLong(1l));
    ValuesULL.push_back(wxULongLong(0x12345678l));
    ValuesULL.push_back(wxULongLong(0x12345678l, 0xabcdef01l));

    CPPUNIT_ASSERT( TestRW(wxLongLong(0x12345678l)) == wxLongLong(0x12345678l) );
    CPPUNIT_ASSERT( TestRW(wxLongLong(0x12345678l, 0xabcdef01l)) == wxLongLong(0x12345678l, 0xabcdef01l) );
    CPPUNIT_ASSERT( TestMultiRW<wxLongLong>(ValuesLL, &wxDataOutputStream::WriteLL, &wxDataInputStream::ReadLL).IsOk() );
    CPPUNIT_ASSERT( TestMultiRW<wxULongLong>(ValuesULL, &wxDataOutputStream::WriteLL, &wxDataInputStream::ReadLL).IsOk() );
}
Example #18
0
wxDateTime wxTarInputStream::GetHeaderDate(const wxString& key) const
{
    wxString value(GetExtendedHeader(key));

    // try extended header, stored as decimal seconds since the epoch
    if (!value.empty()) {
        wxLongLong ll;
        ll.Assign(wxAtof(value) * 1000.0);
        return ll;
    }

    if (key == wxT("mtime"))
        return wxLongLong(m_hdr->GetOctal(TAR_MTIME)) * 1000L;

    return wxDateTime();
}
Example #19
0
void wxTarOutputStream::SetHeaderDate(const wxString& key,
                                      const wxDateTime& datetime)
{
    wxLongLong ll = datetime.IsValid() ? datetime.GetValue() : wxLongLong(0);
    wxLongLong secs = ll / 1000L;

    if (key != wxT("mtime")
        || !m_hdr->SetOctal(TAR_MTIME, wxTarNumber(secs.GetValue()))
        || secs <= 0 || secs >= 0x7fffffff)
    {
        wxString str;
        if (ll >= LONG_MIN && ll <= LONG_MAX) {
            str.Printf(wxT("%g"), ll.ToLong() / 1000.0);
        } else {
            str = ll.ToString();
            str.insert(str.end() - 3, '.');
        }
        SetExtendedHeader(key, str);
    }
}
Example #20
0
bool WXCTimer::Start (const wxDateTime& timeNextWakeUp)
{
    timeNextWakeUp_ = wxInvalidDateTime;

    // valid?
    if (timeNextWakeUp < wxDateTime::Now())
        return false;

    // get intervall in milliseconds
    wxLongLong llMsec = timeNextWakeUp.Subtract(wxDateTime::Now()).GetMilliseconds();

    // take care of the maximum value for 'int'
    if (llMsec > wxLongLong(0, INT_MAX))
    {
        timeNextWakeUp_ = timeNextWakeUp;

        return wxTimer::Start(INT_MAX, wxTIMER_ONE_SHOT);
    }

    return wxTimer::Start(llMsec.ToLong(), wxTIMER_ONE_SHOT);
}
Example #21
0
bool PreferenceFileUtil::saveAccessToken(const AccessToken& accessToken, bool overWrite) {
	wxFile file;
	if(!file.Create(ACCESS_TOKEN_SAVE_FILE,overWrite)){
		//ファイルの作成に失敗
		return false;
	}

	//ファイルに書き出すための文字列を作る
	wxString str = wxLongLong(accessToken.getUserId()).ToString();
	str += "\t";
	str += *accessToken.getScreenName();
	str += "\t";
	str += *accessToken.getToken();
	str += "\t";
	str += *accessToken.getTokenSecret();

	file.Write(str);
	file.Close();

	return true;
}
Example #22
0
/* static */
void VSTEffect::Scan()
{
   wxArrayString audacityPathList = wxGetApp().audacityPathList;
   wxArrayString pathList;
   wxArrayString files;

   // Check for the VST_PATH environment variable
   wxString vstpath = wxGetenv(wxT("VST_PATH"));
   if (!vstpath.IsEmpty()) {
      wxGetApp().AddUniquePathToPathList(vstpath, pathList);
   }

   // Add Audacity specific paths
   for (size_t i = 0; i < audacityPathList.GetCount(); i++) {
      wxString prefix = audacityPathList[i] + wxFILE_SEP_PATH;
      wxGetApp().AddUniquePathToPathList(prefix + VSTPLUGINTYPE,
                                         pathList);
      wxGetApp().AddUniquePathToPathList(prefix + wxT("plugins"),
                                         pathList);
      wxGetApp().AddUniquePathToPathList(prefix + wxT("plug-ins"),
                                         pathList);
   }

#if defined(__WXMAC__)
#define VSTPATH wxT("/Library/Audio/Plug-Ins/VST")

   // Look in /Library/Audio/Plug-Ins/VST and $HOME/Library/Audio/Plug-Ins/VST
   wxGetApp().AddUniquePathToPathList(VSTPATH, pathList);
   wxGetApp().AddUniquePathToPathList(wxString(wxGetenv(wxT("HOME"))) + VSTPATH,
                                      pathList);

   // Recursively search all paths for Info.plist files.  This will identify all
   // bundles.
   wxGetApp().FindFilesInPathList(wxT("Info.plist"), pathList, files, wxDIR_DEFAULT);

   // Remove the 'Contents/Info.plist' portion of the names
   for (size_t i = 0, cnt = files.GetCount(); i < cnt; i++) {
      files[i] = wxPathOnly(wxPathOnly(files[i]));
   }
   
#elif defined(__WXMSW__)
   TCHAR dpath[MAX_PATH];
   TCHAR tpath[MAX_PATH];
   DWORD len = WXSIZEOF(tpath);

   // Setup the default VST path.
   dpath[0] = '\0';
   ExpandEnvironmentStrings(wxT("%ProgramFiles%\\Steinberg\\VSTPlugins"),
                            dpath,
                            WXSIZEOF(dpath));

   // Check registry for the real path
   if (SHRegGetUSValue(wxT("Software\\VST"),
                          wxT("VSTPluginsPath"),
                          NULL,
                          tpath,
                          &len,
                          FALSE,
                          dpath,
                          (DWORD) _tcslen(dpath)) == ERROR_SUCCESS) {
      tpath[len] = 0;
      ExpandEnvironmentStrings(tpath, dpath, WXSIZEOF(dpath));
      wxGetApp().AddUniquePathToPathList(LAT1CTOWX(dpath), pathList);
   }

   // Recursively scan for all DLLs
   wxGetApp().FindFilesInPathList(wxT("*.dll"), pathList, files, wxDIR_DEFAULT);

#else

   // Recursively scan for all shared objects
   wxGetApp().FindFilesInPathList(wxT("*.so"), pathList, files);

#endif

   // This is a hack to allow for long paths in the progress dialog.  The
   // progress dialog should really truncate the message if it's too wide
   // for the dialog.
   size_t cnt = files.GetCount();
   wxString longest;

   // JKC: Let's not show the progress dialog if there are no 
   // files to test.
   if( cnt <= 0 )
      return;

   for (size_t i = 0; i < cnt; i++) {
      if (files[i].Length() > longest.Length()) {
         longest = files[i];
      }
   }

   ProgressDialog *progress = new ProgressDialog(_("Scanning VST Plugins"),
                                                 longest,
                                                 pdlgHideStopButton);
//   progress->SetSize(wxSize(500, -1));
   progress->CenterOnScreen();

   const wxChar * argv[4];
   argv[0] = PlatformCompatibility::GetExecutablePath().c_str();
   argv[1] = VSTCMDKEY;
   argv[2] = NULL;
   argv[3] = NULL;

   for (size_t i = 0; i < cnt; i++) {
      wxString file = files[i];
      int status = progress->Update(wxLongLong(i),
                                    wxLongLong(cnt),
                                    wxString::Format(_("Checking %s"), file.c_str()));
      if (status != eProgressSuccess) {
         break;
      }

      argv[2] = file.c_str();
      // ToDo: do we need a try--catch around this in case a bad plug-in 
      // fails? (JKC Nov09)
      wxExecute((wxChar **) argv, wxEXEC_SYNC | wxEXEC_NODISABLE, NULL);
   }

   delete progress;   
}
Example #23
0
bool CLocalFileSystem::GetNextFile(wxString& name, bool &isLink, bool &is_dir, wxLongLong* size, CDateTime* modificationTime, int* mode)
{
#ifdef __WXMSW__
	if (!m_found)
		return false;
	do
	{
		if (!m_find_data.cFileName[0]) {
			m_found = FindNextFile(m_hFind, &m_find_data) != 0;
			return true;
		}
		if (m_dirs_only && !(m_find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
			continue;

		if (m_find_data.cFileName[0] == '.' && (!m_find_data.cFileName[1] || (m_find_data.cFileName[1] == '.' && !m_find_data.cFileName[2])))
			continue;
		name = m_find_data.cFileName;

		is_dir = (m_find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

		isLink = (m_find_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
		if (isLink) {
			HANDLE hFile = is_dir ? INVALID_HANDLE_VALUE : CreateFile(m_find_path + name, FILE_READ_ATTRIBUTES | FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
			if (hFile != INVALID_HANDLE_VALUE) {
				BY_HANDLE_FILE_INFORMATION info{};
				int ret = GetFileInformationByHandle(hFile, &info);
				CloseHandle(hFile);
				if (ret != 0 && !(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {

					if (modificationTime) {
						if (!ConvertFileTimeToCDateTime(*modificationTime, info.ftLastWriteTime))
							ConvertFileTimeToCDateTime(*modificationTime, info.ftCreationTime);
					}

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

					is_dir = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
					if (size) {
						if (is_dir) {
							*size = -1;
						}
						else {
							*size = wxLongLong(info.nFileSizeHigh, info.nFileSizeLow);
						}
					}

					m_found = FindNextFile(m_hFind, &m_find_data) != 0;
					return true;
				}
			}

			if (m_dirs_only && !is_dir) {
				continue;
			}

			if (size)
				*size = -1;
			if (mode)
				*mode = 0;
			if (modificationTime)
				*modificationTime = CDateTime();
		}
		else {
			if (modificationTime)
				ConvertFileTimeToCDateTime(*modificationTime, m_find_data.ftLastWriteTime);

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

			if (size) {
				if (is_dir) {
					*size = -1;
				}
				else {
					*size = wxLongLong(m_find_data.nFileSizeHigh, m_find_data.nFileSizeLow);
				}
			}
		}
		m_found = FindNextFile(m_hFind, &m_find_data) != 0;
		return true;
	} while ((m_found = FindNextFile(m_hFind, &m_find_data) != 0));

	return false;
#else
	if (!m_dir)
		return false;

	struct dirent* entry;
	while ((entry = readdir(m_dir)))
	{
		if (!entry->d_name[0] ||
			!strcmp(entry->d_name, ".") ||
			!strcmp(entry->d_name, ".."))
			continue;

#if HAVE_STRUCT_DIRENT_D_TYPE
		if (m_dirs_only)
		{
			if (entry->d_type == DT_LNK)
			{
				AllocPathBuffer(entry->d_name);
				strcpy(m_file_part, entry->d_name);
				enum local_fileType type = GetFileInfo(m_raw_path, isLink, size, modificationTime, mode);
				if (type != dir)
					continue;

				name = wxString(entry->d_name, *wxConvFileName);
				is_dir = true;
				return true;
			}
			else if (entry->d_type != DT_DIR)
				continue;
		}
#endif

		AllocPathBuffer(entry->d_name);
		strcpy(m_file_part, entry->d_name);
		enum local_fileType type = GetFileInfo(m_raw_path, isLink, size, modificationTime, mode);

		if (type == unknown) // Happens for example in case of permission denied
		{
#if HAVE_STRUCT_DIRENT_D_TYPE
			type = entry->d_type == DT_DIR ? dir : file;
#else
			type = file;
#endif
			isLink = 0;
			if (size)
				*size = -1;
			if (modificationTime)
				*modificationTime = CDateTime();
			if (mode)
				*mode = 0;
		}
		if (m_dirs_only && type != dir)
			continue;

		is_dir = type == dir;

		name = wxString(entry->d_name, *wxConvFileName);

		return true;
	}

	return false;
#endif
}
Example #24
0
enum CLocalFileSystem::local_fileType CLocalFileSystem::GetFileInfo(const wxString& path, bool &isLink, wxLongLong* size, CDateTime* modificationTime, int *mode)
{
#ifdef __WXMSW__
	if (path.Last() == wxFileName::GetPathSeparator() && path != wxFileName::GetPathSeparator()) {
		wxString tmp = path;
		tmp.RemoveLast();
		return GetFileInfo(tmp, isLink, size, modificationTime, mode);
	}

	isLink = false;

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

	bool is_dir = (attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;

	if (attributes.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
		isLink = true;

		HANDLE hFile = is_dir ? INVALID_HANDLE_VALUE : CreateFile(path, FILE_READ_ATTRIBUTES | FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
		if (hFile != INVALID_HANDLE_VALUE) {
			BY_HANDLE_FILE_INFORMATION info{};
			int ret = GetFileInformationByHandle(hFile, &info);
			CloseHandle(hFile);
			if (ret != 0 && !(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) {

				if (modificationTime) {
					if (!ConvertFileTimeToCDateTime(*modificationTime, info.ftLastWriteTime))
						ConvertFileTimeToCDateTime(*modificationTime, info.ftCreationTime);
				}

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

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

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

				return file;
			}
		}

		if (size)
			*size = -1;
		if (mode)
			*mode = 0;
		if (modificationTime)
			*modificationTime = CDateTime();
		return is_dir ? dir : unknown;
	}

	if (modificationTime) {
		if (!ConvertFileTimeToCDateTime(*modificationTime, attributes.ftLastWriteTime))
			ConvertFileTimeToCDateTime(*modificationTime, attributes.ftCreationTime);
	}

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

	if (is_dir) {
		if (size)
			*size = -1;
		return dir;
	}
	else {
		if (size)
			*size = wxLongLong(attributes.nFileSizeHigh, attributes.nFileSizeLow);
		return file;
	}
#else
	if (path.Last() == '/' && path != _T("/"))
	{
		wxString tmp = path;
		tmp.RemoveLast();
		return GetFileInfo(tmp, isLink, size, modificationTime, mode);
	}

	const wxCharBuffer p = path.fn_str();
	return GetFileInfo((const char*)p, isLink, size, modificationTime, mode);
#endif
}
Example #25
0
WXDLLEXPORT bool
wxConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant)
{
    bool ok = true;
    if ( oleVariant.vt & VT_ARRAY )
    {

        // Compute the total number of elements in all array dimensions
        int cElements = 1;
        for ( int cDims = 0; cDims < oleVariant.parray->cDims; cDims++ )
            cElements *= oleVariant.parray->rgsabound[cDims].cElements;

        // Get a pointer to the data
        void* pvdata;
        HRESULT hr = SafeArrayAccessData(oleVariant.parray, &pvdata);
        if ( FAILED(hr) )
            return false;

        switch (oleVariant.vt & VT_TYPEMASK)
        {
        case VT_VARIANT:
        {
            variant.ClearList();
            VARIANTARG *variant_data=(VARIANTARG*)pvdata;
            for ( int i = 0; i < cElements; i++ )
            {
                VARIANTARG& oleElement = variant_data[i];
                wxVariant vElement;
                if ( !wxConvertOleToVariant(oleElement, vElement) )
                {
                    ok = false;
                    variant.ClearList();
                    break;
                }

                variant.Append(vElement);
            }
        }
        break;

        case VT_BSTR:
        {
            wxArrayString strings;
            BSTR *string_val=(BSTR*)pvdata;
            for ( int i = 0; i < cElements; ++i )
            {
                wxString str=wxConvertStringFromOle(*string_val);
                strings.Add(str);
                ++string_val;
            }
            variant=strings;
        }
        break;

        default:
            wxLogDebug(wxT("unhandled VT_ARRAY type %x in wxConvertOleToVariant"),
                       oleVariant.vt & VT_TYPEMASK);
            variant = wxVariant();
            ok = false;
            break;
        }

        SafeArrayUnaccessData(oleVariant.parray);
    }
    else if ( oleVariant.vt & VT_BYREF )
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
        case VT_VARIANT:
        {
            VARIANTARG& oleReference = *((LPVARIANT)oleVariant.byref);
            if (!wxConvertOleToVariant(oleReference,variant))
                return false;
            break;
        }

        default:
            wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: [as yet] unhandled reference %X"),
                       oleVariant.vt);
            return false;
        }
    }
    else // simply type (not array or reference)
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
        case VT_BSTR:
        {
            wxString str(wxConvertStringFromOle(oleVariant.bstrVal));
            variant = str;
        }
        break;

        case VT_DATE:
#if wxUSE_DATETIME
        {
            SYSTEMTIME st;
            VariantTimeToSystemTime(oleVariant.date, &st);

            wxDateTime date;
            date.SetFromMSWSysTime(st);
            variant = date;
        }
#endif // wxUSE_DATETIME
        break;

            // See the comment before the __VISUALC6__ test above.
#if wxUSE_LONGLONG && !defined(__VISUALC6__)
        case VT_I8:
            variant = wxLongLong(oleVariant.llVal);
            break;
#endif // wxUSE_LONGLONG

        case VT_I4:
            variant = (long) oleVariant.lVal;
            break;

        case VT_I2:
            variant = (long) oleVariant.iVal;
            break;

        case VT_BOOL:
            variant = oleVariant.boolVal != 0;
            break;

        case VT_R4:
            variant = oleVariant.fltVal;
            break;

        case VT_R8:
            variant = oleVariant.dblVal;
            break;

        case VT_DISPATCH:
            variant = (void*) oleVariant.pdispVal;
            break;

        case VT_NULL:
            variant.MakeNull();
            break;

        case VT_EMPTY:
            break;    // Ignore Empty Variant, used only during destruction of objects

        default:
            wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: Unknown variant value type %X -> %X"),
                       oleVariant.vt,oleVariant.vt&VT_TYPEMASK);
            return false;
        }
    }

    return ok;
}
Example #26
0
WXDLLEXPORT bool
wxConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant)
{
    bool ok = true;
    if ( oleVariant.vt & VT_ARRAY )
    {
        // TODO: We currently return arrays as wxVariant of the list type
        //       containing the flattened form of array but we should allow
        //       getting it as wxVariantDataSafeArray instead. Doing this is
        //       simple, we'd just need to do something like this:
        //
        //  if ( oleVariant.parray && SafeArrayGetDim(oleVariant.parray) > 1 )
        //  {
        //      variant.SetData(new wxVariantDataSafeArray(oleVariant.parray));
        //  }
        //
        //      but currently we don't do it for compatibility reasons.
        switch (oleVariant.vt & VT_TYPEMASK)
        {
            case VT_I2:
                ok = wxSafeArray<VT_I2>::ConvertToVariant(oleVariant.parray, variant);
                break;
            case VT_I4:
                ok = wxSafeArray<VT_I4>::ConvertToVariant(oleVariant.parray, variant);
                break;
            case VT_R4:
                ok = wxSafeArray<VT_R4>::ConvertToVariant(oleVariant.parray, variant);
                break;
            case VT_R8:
                ok = wxSafeArray<VT_R8>::ConvertToVariant(oleVariant.parray, variant);
                break;
            case VT_VARIANT:
                ok = wxSafeArray<VT_VARIANT>::ConvertToVariant(oleVariant.parray, variant);
                break;
            case VT_BSTR:
                {
                    wxArrayString strings;
                    if ( wxSafeArray<VT_BSTR>::ConvertToArrayString(oleVariant.parray, strings) )
                        variant = strings;
                    else
                        ok = false;
                }
                break;
            default:
                ok = false;
                break;
        }
        if ( !ok )
        {
            wxLogDebug(wxT("unhandled VT_ARRAY type %x in wxConvertOleToVariant"),
                       oleVariant.vt & VT_TYPEMASK);
            variant = wxVariant();
        }
    }
    else if ( oleVariant.vt & VT_BYREF )
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
            case VT_VARIANT:
                {
                    VARIANTARG& oleReference = *((LPVARIANT)oleVariant.byref);
                    if (!wxConvertOleToVariant(oleReference,variant))
                        return false;
                    break;
                }

            default:
                wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: [as yet] unhandled reference %X"),
                            oleVariant.vt);
                return false;
        }
    }
    else // simply type (not array or reference)
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
            case VT_ERROR:
                variant.SetData(new wxVariantDataErrorCode(oleVariant.scode));
                break;

            case VT_CY:
                variant.SetData(new wxVariantDataCurrency(oleVariant.cyVal));
                break;

            case VT_BSTR:
                {
                    wxString str(wxConvertStringFromOle(oleVariant.bstrVal));
                    variant = str;
                }
                break;

            case VT_DATE:
#if wxUSE_DATETIME
                {
                    SYSTEMTIME st;
                    VariantTimeToSystemTime(oleVariant.date, &st);

                    wxDateTime date;
                    date.SetFromMSWSysTime(st);
                    variant = date;
                }
#endif // wxUSE_DATETIME
                break;

                // See the comment before the __VISUALC6__ test above.
#if wxUSE_LONGLONG && !defined(__VISUALC6__)
            case VT_I8:
                variant = wxLongLong(oleVariant.llVal);
                break;
#endif // wxUSE_LONGLONG

            case VT_I4:
                variant = (long) oleVariant.lVal;
                break;

            case VT_I2:
                variant = (long) oleVariant.iVal;
                break;

            case VT_BOOL:
                variant = oleVariant.boolVal != 0;
                break;

            case VT_R4:
                variant = oleVariant.fltVal;
                break;

            case VT_R8:
                variant = oleVariant.dblVal;
                break;

            case VT_DISPATCH:
                variant = (void*) oleVariant.pdispVal;
                break;

            case VT_NULL:
                variant.MakeNull();
                break;

            case VT_EMPTY:
                break;    // Ignore Empty Variant, used only during destruction of objects

            default:
                wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: Unknown variant value type %X -> %X"),
                           oleVariant.vt,oleVariant.vt&VT_TYPEMASK);
                return false;
        }
    }

    return ok;
}
Example #27
0
bool wxGetDiskSpace(const wxString& WXUNUSED_IN_WINCE(path),
                    wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pTotal),
                    wxDiskspaceSize_t *WXUNUSED_IN_WINCE(pFree))
{
#ifdef __WXWINCE__
    // TODO-CE
    return false;
#else
    if ( path.empty() )
        return false;

// old w32api don't have ULARGE_INTEGER
#if defined(__WIN32__) && \
    (!defined(__GNUWIN32__) || wxCHECK_W32API_VERSION( 0, 3 ))
    // GetDiskFreeSpaceEx() is not available under original Win95, check for
    // it
    typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
                                                PULARGE_INTEGER,
                                                PULARGE_INTEGER,
                                                PULARGE_INTEGER);

    GetDiskFreeSpaceEx_t
        pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
                              (
                                ::GetModuleHandle(_T("kernel32.dll")),
#if wxUSE_UNICODE
                                "GetDiskFreeSpaceExW"
#else
                                "GetDiskFreeSpaceExA"
#endif
                              );

    if ( pGetDiskFreeSpaceEx )
    {
        ULARGE_INTEGER bytesFree, bytesTotal;

        // may pass the path as is, GetDiskFreeSpaceEx() is smart enough
        if ( !pGetDiskFreeSpaceEx(path,
                                  &bytesFree,
                                  &bytesTotal,
                                  NULL) )
        {
            wxLogLastError(_T("GetDiskFreeSpaceEx"));

            return false;
        }

        // ULARGE_INTEGER is a union of a 64 bit value and a struct containing
        // two 32 bit fields which may be or may be not named - try to make it
        // compile in all cases
#if defined(__BORLANDC__) && !defined(_ANONYMOUS_STRUCT)
        #define UL(ul) ul.u
#else // anon union
        #define UL(ul) ul
#endif
        if ( pTotal )
        {
#if wxUSE_LONGLONG
            *pTotal = wxDiskspaceSize_t(UL(bytesTotal).HighPart, UL(bytesTotal).LowPart);
#else
            *pTotal = wxDiskspaceSize_t(UL(bytesTotal).LowPart);
#endif
        }

        if ( pFree )
        {
#if wxUSE_LONGLONG
            *pFree = wxLongLong(UL(bytesFree).HighPart, UL(bytesFree).LowPart);
#else
            *pFree = wxDiskspaceSize_t(UL(bytesFree).LowPart);
#endif
        }
    }
    else
#endif // Win32
    {
        // there's a problem with drives larger than 2GB, GetDiskFreeSpaceEx()
        // should be used instead - but if it's not available, fall back on
        // GetDiskFreeSpace() nevertheless...

        DWORD lSectorsPerCluster,
              lBytesPerSector,
              lNumberOfFreeClusters,
              lTotalNumberOfClusters;

        // FIXME: this is wrong, we should extract the root drive from path
        //        instead, but this is the job for wxFileName...
        if ( !::GetDiskFreeSpace(path,
                                 &lSectorsPerCluster,
                                 &lBytesPerSector,
                                 &lNumberOfFreeClusters,
                                 &lTotalNumberOfClusters) )
        {
            wxLogLastError(_T("GetDiskFreeSpace"));

            return false;
        }

        wxDiskspaceSize_t lBytesPerCluster = (wxDiskspaceSize_t) lSectorsPerCluster;
        lBytesPerCluster *= lBytesPerSector;

        if ( pTotal )
        {
            *pTotal = lBytesPerCluster;
            *pTotal *= lTotalNumberOfClusters;
        }

        if ( pFree )
        {
            *pFree = lBytesPerCluster;
            *pFree *= lNumberOfFreeClusters;
        }
    }

    return true;
#endif
    // __WXWINCE__
}
Example #28
0
void wxAnyTestCase::wxVariantConversions()
{
#if wxUSE_VARIANT
    //
    // Test various conversions to and from wxVariant
    //
    bool res;

    // Prepare wxVariants
    wxVariant vLong(123L);
    wxVariant vString("ABC");
    wxVariant vDouble(TEST_FLOAT_CONST);
    wxVariant vBool((bool)true);
    wxVariant vChar('A');
#ifdef wxLongLong_t
    wxVariant vLongLong(wxLongLong(wxLL(0xAABBBBCCCC)));
    wxVariant vULongLong(wxULongLong(wxULL(123456)));
#endif
    wxArrayString arrstr;
    arrstr.push_back("test string");
    wxVariant vArrayString(arrstr);
    wxVariant vDateTime(m_testDateTime);
    wxVariant vVoidPtr(dummyVoidPointer);
    wxVariant vCustomType(new wxMyVariantData(MyClass(101)));
    wxVariant vList;

    vList.NullList();
    vList.Append(15);
    vList.Append("abc");

    // Convert to wxAnys, and then back to wxVariants
    wxVariant variant;

    wxAny any(vLong);
    CPPUNIT_ASSERT(any == 123L);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant == 123L);

    // Make sure integer variant has correct type information
    CPPUNIT_ASSERT(variant.GetLong() == 123);
    CPPUNIT_ASSERT(variant.GetType() == "long");

    // Unsigned long wxAny should convert to "ulonglong" wxVariant
    any = 1000UL;
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "ulonglong");
    CPPUNIT_ASSERT(variant.GetLong() == 1000);

    any = vString;
    CPPUNIT_ASSERT(any == "ABC");
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetString() == "ABC");

    // Must be able to build string wxVariant from wxAny built from
    // string literal
    any = "ABC";
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "string");
    CPPUNIT_ASSERT(variant.GetString() == "ABC");
    any = L"ABC";
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "string");
#if wxUSE_UNICODE
    CPPUNIT_ASSERT(variant.GetString() == L"ABC");
#endif

    any = vDouble;
    double d = wxANY_AS(any, double);
    CPPUNIT_ASSERT_DOUBLES_EQUAL(d, TEST_FLOAT_CONST, FEQ_DELTA);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT_DOUBLES_EQUAL(variant.GetDouble(),
                                 TEST_FLOAT_CONST,
                                 FEQ_DELTA);

    any = vBool;
    CPPUNIT_ASSERT(wxANY_AS(any, bool) == true);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetBool() == true);

    any = wxAny(vChar);
    //CPPUNIT_ASSERT(wxANY_AS(any, wxUniChar) == 'A');
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetChar() == 'A');

#ifdef wxLongLong_t
    any = wxAny(vLongLong);
    CPPUNIT_ASSERT(any == wxLL(0xAABBBBCCCC));
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "longlong");
    CPPUNIT_ASSERT(variant.GetLongLong() == wxLongLong(wxLL(0xAABBBBCCCC)));

#if LONG_MAX == wxINT64_MAX
    // As a sanity check, test that wxVariant of type 'long' converts
    // seamlessly to 'longlong' (on some 64-bit systems)
    any = 0xAABBBBCCCCL;
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(variant.GetLongLong() == wxLongLong(wxLL(0xAABBBBCCCC)));
#endif

    any = wxAny(vULongLong);
    CPPUNIT_ASSERT(any == wxLL(123456));
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "ulonglong");
    CPPUNIT_ASSERT(variant.GetULongLong() == wxULongLong(wxULL(123456)));
#endif

    // Cannot test equality for the rest, just test that they convert
    // back correctly.
    any = wxAny(vArrayString);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    wxArrayString arrstr2 = variant.GetArrayString();
    CPPUNIT_ASSERT(arrstr2 == arrstr);

    any = m_testDateTime;
    CPPUNIT_ASSERT(wxANY_AS(any, wxDateTime) == m_testDateTime);
    any = wxAny(vDateTime);
    CPPUNIT_ASSERT(wxANY_AS(any, wxDateTime) == m_testDateTime);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant == m_testDateTime);

    any = wxAny(vVoidPtr);
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetVoidPtr() == dummyVoidPointer);

    any = wxAny(vList);
    CPPUNIT_ASSERT(wxANY_CHECK_TYPE(any, wxAnyList));
    wxAnyList anyList = wxANY_AS(any, wxAnyList);
    CPPUNIT_ASSERT(anyList.GetCount() == 2);
    CPPUNIT_ASSERT(wxANY_AS((*anyList[0]), int) == 15);
    CPPUNIT_ASSERT(wxANY_AS((*anyList[1]), wxString) == "abc");
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "list");
    CPPUNIT_ASSERT(variant.GetCount() == 2);
    CPPUNIT_ASSERT(variant[0].GetLong() == 15);
    CPPUNIT_ASSERT(variant[1].GetString() == "abc");

    any = wxAny(vCustomType);
    CPPUNIT_ASSERT(wxANY_CHECK_TYPE(any, wxVariantData*));
    res = any.GetAs(&variant);
    CPPUNIT_ASSERT(res);
    CPPUNIT_ASSERT(variant.GetType() == "MyClass");

#endif // wxUSE_VARIANT
}
Example #29
0
WXDLLEXPORT bool
wxConvertOleToVariant(const VARIANTARG& oleVariant, wxVariant& variant, long flags)
{
    bool ok = true;
    if ( oleVariant.vt & VT_ARRAY )
    {
        if ( flags & wxOleConvertVariant_ReturnSafeArrays  )
        {
            variant.SetData(new wxVariantDataSafeArray(oleVariant.parray));
        }
        else
        {
            switch (oleVariant.vt & VT_TYPEMASK)
            {
                case VT_I2:
                    ok = wxSafeArray<VT_I2>::ConvertToVariant(oleVariant.parray, variant);
                    break;
                case VT_I4:
                    ok = wxSafeArray<VT_I4>::ConvertToVariant(oleVariant.parray, variant);
                    break;
                case VT_R4:
                    ok = wxSafeArray<VT_R4>::ConvertToVariant(oleVariant.parray, variant);
                    break;
                case VT_R8:
                    ok = wxSafeArray<VT_R8>::ConvertToVariant(oleVariant.parray, variant);
                    break;
                case VT_VARIANT:
                    ok = wxSafeArray<VT_VARIANT>::ConvertToVariant(oleVariant.parray, variant);
                    break;
                case VT_BSTR:
                    {
                        wxArrayString strings;
                        if ( wxSafeArray<VT_BSTR>::ConvertToArrayString(oleVariant.parray, strings) )
                            variant = strings;
                        else
                            ok = false;
                    }
                    break;
                default:
                    ok = false;
                    break;
            }
            if ( !ok )
            {
                wxLogDebug(wxT("unhandled VT_ARRAY type %x in wxConvertOleToVariant"),
                           oleVariant.vt & VT_TYPEMASK);
                variant = wxVariant();
            }
        }
    }
    else if ( oleVariant.vt & VT_BYREF )
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
            case VT_VARIANT:
                {
                    VARIANTARG& oleReference = *((LPVARIANT)oleVariant.byref);
                    if (!wxConvertOleToVariant(oleReference,variant))
                        return false;
                    break;
                }

            default:
                wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: [as yet] unhandled reference %X"),
                            oleVariant.vt);
                return false;
        }
    }
    else // simply type (not array or reference)
    {
        switch ( oleVariant.vt & VT_TYPEMASK )
        {
            case VT_ERROR:
                variant.SetData(new wxVariantDataErrorCode(oleVariant.scode));
                break;

            case VT_CY:
                variant.SetData(new wxVariantDataCurrency(oleVariant.cyVal));
                break;

            case VT_BSTR:
                {
                    wxString str(wxConvertStringFromOle(oleVariant.bstrVal));
                    variant = str;
                }
                break;

            case VT_DATE:
#if wxUSE_DATETIME
                {
                    SYSTEMTIME st;
                    VariantTimeToSystemTime(oleVariant.date, &st);

                    wxDateTime date;
                    date.SetFromMSWSysTime(st);
                    variant = date;
                }
#endif // wxUSE_DATETIME
                break;

#if wxUSE_LONGLONG
            case VT_I8:
                variant = wxLongLong(oleVariant.llVal);
                break;
#endif // wxUSE_LONGLONG

            case VT_I4:
                variant = (long) oleVariant.lVal;
                break;

            case VT_I2:
                variant = (long) oleVariant.iVal;
                break;

            case VT_BOOL:
                variant = oleVariant.boolVal != 0;
                break;

            case VT_R4:
                variant = oleVariant.fltVal;
                break;

            case VT_R8:
                variant = oleVariant.dblVal;
                break;

            case VT_DISPATCH:
                variant = (void*) oleVariant.pdispVal;
                break;

            case VT_NULL:
            case VT_EMPTY:
                variant.MakeNull();
                break;

            default:
                wxLogError(wxT("wxAutomationObject::ConvertOleToVariant: Unknown variant value type %X -> %X"),
                           oleVariant.vt,oleVariant.vt&VT_TYPEMASK);
                return false;
        }
    }

    return ok;
}
Example #30
0
int main(int argc, char **argv) {
    wxInitializer wx_initializer;
    if ( !wx_initializer ) {
        fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
        return -1;
    }
    wxCmdLineParser cmd_parser(cmdLineDesc, argc, argv);
    
    long run_count = 10;
    wxString grid_path, dict_path;
    
    bool is_rand    = false;
    bool is_verbose = false;
    
    switch ( cmd_parser.Parse() ) {
        case -1:
            return 0;
        case 0:
            cmd_parser.Found(wxT("count"), &run_count);
            is_rand    = cmd_parser.Found(wxT("rand"));
            is_verbose = cmd_parser.Found(wxT("verbose"));
            grid_path  = cmd_parser.GetParam(0);
            dict_path  = cmd_parser.GetParam(1);
            wxLogDebug(wxT("grid_path = ") + grid_path + wxT("\n"));
            wxLogDebug(wxT("dict_path = ") + dict_path + wxT("\n"));
            wxLogDebug(wxT("run_count = %d\n"), run_count);
            break;
        default:
            return 0;
    }
    std::vector< wxLongLong > durs(run_count); // durations
    std::vector< wxString > words_out;
    DictType dict;
    GridType grid;
    AllWordsType all_words;
    CharsTransType trans_type;
    
    readDict(dict_path, dict);
    generateAllWords(dict, all_words, trans_type);
    readGrid(grid_path, grid);
    
    if ( is_rand )
        srand(time(NULL));
    
    for (long i = 0; i < run_count; ++i) {
        if ( !is_rand )
            srand(42);
        words_out.clear();
        durs.at(i) = wxGetLocalTimeMillis();
        generateCross(grid,all_words,trans_type,words_out);
        if ( words_out.size() == 0 )
            wxPrintf(wxT("Error in creating #%-2i!\n"),i+1);
        durs.at(i) = wxGetLocalTimeMillis() - durs.at(i);
        if ( is_verbose )
            wxPrintf(wxT("Time to generate  #%-2i is ") 
                + durs.at(i).ToString() + wxT(" ms\n"), i+1);
    }
    wxLongLong tm_total = std::accumulate(durs.begin(),durs.end(), wxLongLong(0,0));
    wxLongLong tm_mean  = (tm_total + run_count/2) / run_count;
    wxPrintf(wxT("Total time = ") + tm_total.ToString() + wxT(" ms.\nMean time  = ") 
        + tm_mean.ToString() + wxT(" ms.\n"));
    return 0;
}