Example #1
0
bool wxFFile::Seek(wxFileOffset ofs, wxSeekMode mode)
{
    wxCHECK_MSG( IsOpened(), false, wxT("can't seek on closed file") );

    int origin;
    switch ( mode )
    {
        default:
            wxFAIL_MSG(wxT("unknown seek mode"));
            // still fall through

        case wxFromStart:
            origin = SEEK_SET;
            break;

        case wxFromCurrent:
            origin = SEEK_CUR;
            break;

        case wxFromEnd:
            origin = SEEK_END;
            break;
    }

#ifndef wxHAS_LARGE_FFILES
    if ((long)ofs != ofs)
    {
        wxLogError(_("Seek error on file '%s' (large files not supported by stdio)"), m_name.c_str());

        return false;
    }

    if ( wxFseek(m_fp, (long)ofs, origin) != 0 )
#else
    if ( wxFseek(m_fp, ofs, origin) != 0 )
#endif
    {
        wxLogSysError(_("Seek error on file '%s'"), m_name.c_str());

        return false;
    }

    return true;
}
Example #2
0
bool wxEpollDispatcher::ModifyFD(int fd, wxFDIOHandler* handler, int flags)
{
    epoll_event ev;
    ev.events = GetEpollMask(flags, fd);
    ev.data.ptr = handler;

    const int ret = epoll_ctl(m_epollDescriptor, EPOLL_CTL_MOD, fd, &ev);
    if ( ret != 0 )
    {
        wxLogSysError(_("Failed to modify descriptor %d in epoll descriptor %d"),
                      fd, m_epollDescriptor);

        return false;
    }

    wxLogTrace(wxEpollDispatcher_Trace,
                wxT("Modified fd %d (handler: %p) on epoll %d"), fd, handler, m_epollDescriptor);
    return true;
}
Example #3
0
bool wxEpollDispatcher::RegisterFD(int fd, wxFDIOHandler* handler, int flags)
{
    epoll_event ev;
    ev.events = GetEpollMask(flags, fd);
    ev.data.ptr = handler;

    const int ret = epoll_ctl(m_epollDescriptor, EPOLL_CTL_ADD, fd, &ev);
    if ( ret != 0 )
    {
        wxLogSysError(_("Failed to add descriptor %d to epoll descriptor %d"),
                      fd, m_epollDescriptor);

        return false;
    }
    wxLogTrace(wxEpollDispatcher_Trace,
               _T("Added fd %d (handler %p) to epoll %d"), fd, handler, m_epollDescriptor);

    return true;
}
Example #4
0
bool wxRegKey::SetValue(const wxString& szValue, const wxMemoryBuffer& buffer)
{
#ifdef __TWIN32__
  wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
  return false;
#else
  if ( CONST_CAST Open() ) {
    m_dwLastError = RegSetValueEx((HKEY) m_hKey, RegValueStr(szValue),
                                  (DWORD) RESERVED, REG_BINARY,
                                  (RegBinary)buffer.GetData(),buffer.GetDataLen());
    if ( m_dwLastError == ERROR_SUCCESS )
      return true;
  }

  wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
                GetFullName(this, szValue));
  return false;
#endif
}
Example #5
0
void wxThreadInternal::Wait()
{
   wxCHECK_RET( !m_isDetached, wxT("can't wait for a detached thread") );

    // if the thread we're waiting for is waiting for the GUI mutex, we will
    // deadlock so make sure we release it temporarily
    if ( wxThread::IsMain() )
    {
        // give the thread we're waiting for chance to do the GUI call
        // it might be in, we don't do this conditionally as the to be waited on
        // thread might have to acquire the mutex later but before terminating
        if ( wxGuiOwnedByMainThread() )
            wxMutexGuiLeave();
    }

    {
        wxCriticalSectionLocker lock(m_csJoinFlag);

        if ( m_shouldBeJoined )
        {
            void *param1, *param2, *rc;

            OSStatus err = MPWaitOnQueue(
                m_notifyQueueId,
                &param1,
                &param2,
                &rc,
                kDurationForever );
            if (err != noErr)
            {
                wxLogSysError( wxT( "Cannot wait for thread termination."));
                rc = (void*) -1;
            }

            // actually param1 would be the address of m_exitcode
            // but we don't need this here
            m_exitcode = rc;

            m_shouldBeJoined = false;
        }
    }
}
Example #6
0
    int ReadEventsToBuf(char* buf, int size)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Inotify not initialized or invalid inotify descriptor" );

        memset(buf, 0, size);
        ssize_t left = read(m_ifd, buf, size);
        if (left == -1)
        {
            wxLogSysError(_("Unable to read from inotify descriptor"));
            return -1;
        }
        else if (left == 0)
        {
            wxLogWarning(_("EOF while reading from inotify descriptor"));
            return -1;
        }

        return left;
    }
Example #7
0
    virtual bool DoRemove(wxSharedPtr<wxFSWatchEntryUnix> watch)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Inotify not initialized or invalid inotify descriptor" );

        int ret = DoRemoveInotify(watch.get());
        if (ret == -1)
        {
            wxLogSysError( _("Unable to remove inotify watch") );
            return false;
        }

        if (m_watchMap.erase(watch->GetWatchDescriptor()) != 1)
        {
            wxFAIL_MSG( wxString::Format("Path %s is not watched",
                                          watch->GetPath()) );
        }
        watch->SetWatchDescriptor(-1);
        return true;
    }
Example #8
0
bool wxThreadInternal::Resume()
{
    ULONG ulrc = ::DosResumeThread(m_hThread);

    if (ulrc != 0)
    {
        wxLogSysError(_("Can not resume thread %lu"), m_hThread);
        return false;
    }

    // don't change the state from STATE_EXITED because it's special and means
    // we are going to terminate without running any user code - if we did it,
    // the codei n Delete() wouldn't work
    if ( m_eState != STATE_EXITED )
    {
        m_eState = STATE_RUNNING;
    }

    return true;
}
Example #9
0
int wxEpollDispatcher::Dispatch(int timeout)
{
    epoll_event events[16];

    const int rc = DoPoll(events, WXSIZEOF(events), timeout);

    if ( rc == -1 )
    {
        wxLogSysError(_("Waiting for IO on epoll descriptor %d failed"),
                      m_epollDescriptor);
        return -1;
    }

    int numEvents = 0;
    for ( epoll_event *p = events; p < events + rc; p++ )
    {
        wxFDIOHandler * const handler = (wxFDIOHandler *)(p->data.ptr);
        if ( !handler )
        {
            wxFAIL_MSG( wxT("NULL handler in epoll_event?") );
            continue;
        }

        // note that for compatibility with wxSelectDispatcher we call
        // OnReadWaiting() on EPOLLHUP as this is what epoll_wait() returns
        // when the write end of a pipe is closed while with select() the
        // remaining pipe end becomes ready for reading when this happens
        if ( p->events & (EPOLLIN | EPOLLHUP) )
            handler->OnReadWaiting();
        else if ( p->events & EPOLLOUT )
            handler->OnWriteWaiting();
        else if ( p->events & EPOLLERR )
            handler->OnExceptionWaiting();
        else
            continue;

        numEvents++;
    }

    return numEvents;
}
Example #10
0
// get current file length
wxFileOffset wxFile::Length() const
{
    wxASSERT( IsOpened() );

    // we use a special method for Linux systems where files in sysfs (i.e.
    // those under /sys typically) return length of 4096 bytes even when
    // they're much smaller -- this is a problem as it results in errors later
    // when we try reading 4KB from them
#ifdef __LINUX__
    struct stat st;
    if ( fstat(m_fd, &st) == 0 )
    {
        // returning 0 for the special files indicates to the caller that they
        // are not seekable
        return st.st_blocks ? st.st_size : 0;
    }
    //else: failed to stat, try the normal method
#endif // __LINUX__

    wxFileOffset iRc = Tell();
    if ( iRc != wxInvalidOffset ) {
        wxFileOffset iLen = const_cast<wxFile *>(this)->SeekEnd();
        if ( iLen != wxInvalidOffset ) {
            // restore old position
            if ( ((wxFile *)this)->Seek(iRc) == wxInvalidOffset ) {
                // error
                iLen = wxInvalidOffset;
            }
        }

        iRc = iLen;
    }

    if ( iRc == wxInvalidOffset )
    {
        // last error was already set by Tell()
        wxLogSysError(_("can't find length of file on file descriptor %d"), m_fd);
    }

    return iRc;
}
Example #11
0
wxMutexError wxMutexInternal::Lock(unsigned long ms)
{
    wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") );

    OSStatus err = MPEnterCriticalRegion( m_critRegion, ms );
    switch ( err )
    {
        case noErr:
            break;

        case kMPTimeoutErr:
            wxASSERT_MSG( ms != kDurationForever, wxT("unexpected timeout") );
            return wxMUTEX_TIMEOUT;

        default:
            wxLogSysError(wxT("Could not lock mutex"));
            return wxMUTEX_MISC_ERROR;
    }

    return wxMUTEX_NO_ERROR;
}
Example #12
0
/* static */
THREAD_RETVAL wxThreadInternal::DoThreadStart(wxThread *thread)
{
    wxON_BLOCK_EXIT1(DoThreadOnExit, thread);

    THREAD_RETVAL rc = THREAD_ERROR_EXIT;

    wxTRY
    {
        // store the thread object in the TLS
        if ( !::TlsSetValue(gs_tlsThisThread, thread) )
        {
            wxLogSysError(_("Cannot start thread: error writing TLS."));

            return THREAD_ERROR_EXIT;
        }

        rc = wxPtrToUInt(thread->Entry());
    }
    wxCATCH_ALL( wxTheApp->OnUnhandledException(); )

    return rc;
Example #13
0
    bool Init()
    {
        wxCHECK_MSG( !IsOk(), false,
                     "Kqueue appears to be already initialized" );

        wxEventLoopBase *loop = wxEventLoopBase::GetActive();
        wxCHECK_MSG( loop, false, "File system watcher needs an active loop" );

        // create kqueue
        m_kfd = kqueue();
        if (m_kfd == -1)
        {
            wxLogSysError(_("Unable to create kqueue instance"));
            return false;
        }

        // create source
        m_source = loop->AddSourceForFD(m_kfd, m_handler, wxEVENT_SOURCE_INPUT);

        return m_source != NULL;
    }
Example #14
0
wxThreadError wxThread::Kill()
{
    if ( !IsRunning() )
        return wxTHREAD_NOT_RUNNING;

//    if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
    {
        wxLogSysError(_("Couldn't terminate thread"));

        return wxTHREAD_MISC_ERROR;
    }

    m_internal->Free();

    if ( IsDetached() )
    {
        delete this;
    }

    return wxTHREAD_NO_ERROR;
}
Example #15
0
bool wxThreadInternal::Suspend()
{
    OSErr err ;

    err = ::ThreadBeginCritical();
    wxASSERT( err == noErr ) ;

    if ( m_state != STATE_RUNNING )
    {
        err = ::ThreadEndCritical() ;
        wxASSERT( err == noErr ) ;
        wxLogSysError(_("Can not suspend thread %x"), m_tid);
        return FALSE;
    }

    m_state = STATE_PAUSED;

    err = ::SetThreadStateEndCritical(m_tid, kStoppedThreadState, kNoThreadID);

    return TRUE;
}
Example #16
0
bool wxOpenClipboard()
{
    wxCHECK_MSG( !gs_wxClipboardIsOpen, true, wxT("clipboard already opened.") );

    wxWindow *win = wxTheApp->GetTopWindow();
    if ( win )
    {
        gs_wxClipboardIsOpen = ::OpenClipboard((HWND)win->GetHWND()) != 0;

        if ( !gs_wxClipboardIsOpen )
            wxLogSysError(_("Failed to open the clipboard."));

        return gs_wxClipboardIsOpen;
    }
    else
    {
        wxLogDebug(wxT("Can not open clipboard without a main window."));

        return false;
    }
}
Example #17
0
/* static */
void wxGUIEventLoop::InitBuffer()
{
    // create DirectFB events buffer:
    ms_buffer = wxIDirectFB::Get()->CreateEventBuffer();

    // and setup a file descriptor that we can watch for new events:

    ms_buffer->CreateFileDescriptor(&ms_bufferFd);
    int flags = fcntl(ms_bufferFd, F_GETFL, 0);
    if ( flags == -1 || fcntl(ms_bufferFd, F_SETFL, flags | O_NONBLOCK) == -1 )
    {
        wxLogSysError(_("Failed to switch DirectFB pipe to non-blocking mode"));
        return;
    }

    wxFDIODispatcher *dispatcher = wxFDIODispatcher::Get();
    wxCHECK_RET( dispatcher, "wxDFB requires wxFDIODispatcher" );

    gs_DFBEventsHandler.SetFD(ms_bufferFd);
    dispatcher->RegisterFD(ms_bufferFd, &gs_DFBEventsHandler, wxFDIO_INPUT);
}
Example #18
0
wxBZipOutputStream::wxBZipOutputStream(wxOutputStream& Stream,
									   wxInt32 nCompressionFactor) : 
    wxFilterOutputStream(Stream)
{
	m_hZip = new bz_stream;

    bz_stream* hZip = (bz_stream*)m_hZip;

	hZip->bzalloc = NULL;
	hZip->bzfree = NULL;
	hZip->opaque = NULL;

	//param 2 - compression factor = 1-9 9 more compression but slower
	//param 3 - verbosity = 0-4, 4 more stuff to stdio (ignored)
	//param 4 - workfactor = reliance on standard comp alg, 0-250, 
    //                                                      0==30 default
	if (BZ2_bzCompressInit(hZip, nCompressionFactor, 0, 0)!= BZ_OK)
	{
		delete hZip;
		wxLogSysError(wxT("Could not initialize bzip compression engine!"));
	}
}
Example #19
0
    virtual bool DoAdd(wxSharedPtr<wxFSWatchEntryUnix> watch)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Inotify not initialized or invalid inotify descriptor" );

        int wd = DoAddInotify(watch.get());
        if (wd == -1)
        {
            wxLogSysError( _("Unable to add inotify watch") );
            return false;
        }

        wxFSWatchEntryDescriptors::value_type val(wd, watch.get());
        if (!m_watchMap.insert(val).second)
        {
            wxFAIL_MSG( wxString::Format( "Path %s is already watched",
                                           watch->GetPath()) );
            return false;
        }

        return true;
    }
Example #20
0
wxBZipInputStream::wxBZipInputStream(wxInputStream& Stream, 
									 bool bLessMemory) : 
    wxFilterInputStream(Stream),
	m_nBufferPos(0)
{
	m_hZip = (void*) new bz_stream;

    bz_stream* hZip = (bz_stream*)m_hZip;
	
    hZip->bzalloc = NULL;
	hZip->bzfree = NULL;
	hZip->opaque = NULL;

	//param 2 - verbosity = 0-4, 4 more stuff to stdio
	//param 3 - small = non-zero means less memory and more time
	if (BZ2_bzDecompressInit(hZip, 0, bLessMemory)!= BZ_OK)
	{
		delete hZip;
		wxLogSysError(wxT("Could not initialize bzip ")
                      wxT("decompression engine!"));
	}
}
Example #21
0
bool wxLaunchDefaultBrowser(const wxString& urlOrig, int flags)
{
    // set the scheme of url to http if it does not have one
    // RR: This doesn't work if the url is just a local path
    wxString url(urlOrig);
    wxURI uri(url);
    if ( !uri.HasScheme() )
    {
        if (wxFileExists(urlOrig))
            url.Prepend( wxT("file://") );
        else
            url.Prepend(wxT("http://"));
    }

    if(s_launchBrowserImpl(url, flags))
        return true;

    wxLogSysError(_T("Failed to open URL \"%s\" in default browser."),
                  url.c_str());

    return false;
}
Example #22
0
bool PipeIOHandler::Create()
{
    if ( !m_pipe.Create() )
    {
        wxLogError(_("Failed to create wake up pipe used by event loop."));
        return false;
    }

    const int fdRead = GetReadFd();

    int flags = fcntl(fdRead, F_GETFL, 0);
    if ( flags == -1 || fcntl(fdRead, F_SETFL, flags | O_NONBLOCK) == -1 )
    {
        wxLogSysError(_("Failed to switch wake up pipe to non-blocking mode"));
        return false;
    }

    wxLogTrace(TRACE_EVENTS, wxT("Wake up pipe (%d, %d) created"),
               fdRead, m_pipe[wxPipe::Write]);

    return true;
}
Example #23
0
    virtual bool DoAdd(wxSharedPtr<wxFSWatchEntryKq> watch)
    {
        wxCHECK_MSG( IsOk(), false,
                    "Kqueue not initialized or invalid kqueue descriptor" );

        struct kevent event;
        int action = EV_ADD | EV_ENABLE | EV_CLEAR | EV_ERROR;
        int flags = Watcher2NativeFlags(watch->GetFlags());
        EV_SET( &event, watch->GetFileDescriptor(), EVFILT_VNODE, action,
                flags, 0, watch.get() );

        // TODO more error conditions according to man
        // TODO best deal with the error here
        int ret = kevent(m_kfd, &event, 1, NULL, 0, NULL);
        if (ret == -1)
        {
            wxLogSysError(_("Unable to add kqueue watch"));
            return false;
        }

        return true;
    }
Example #24
0
wxRarInputStream::wxRarInputStream(const wxChar* szFile)
{
	    RAROpenArchiveDataEx rx;
	    memset(&rx,0,sizeof(rx));
#if wxUSE_UNICODE
        rx.ArcNameW =((wxChar*) szFile);
#else /* !wxUSE_UNICODE */
	    rx.ArcName  =((wxChar*) szFile);
#endif
        rx.OpenMode=RAR_OM_EXTRACT;
	    rx.CmtBuf=m_Info.szComment=new char[2000];
	    rx.CmtBufSize=2000;
	    m_hRar = RAROpenArchiveEx(&rx);

        if (!m_hRar)
        {
            wxLogSysError(wxString::Format(_("Couldn't open rar file %s"), szFile));
            delete m_Info.szComment;
        }

	    RARSetPassword(m_hRar,"");
}
Example #25
0
wxString wxGetCurrentDir()
{
    wxString dir;
    size_t len = 1024;
    bool ok;
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    do
    {
        ok = getcwd(dir.GetWriteBuf(len + 1), len) != NULL;
        dir.UngetWriteBuf();

        if ( !ok )
        {
            if ( errno != ERANGE )
            {
                wxLogSysError(wxT("Failed to get current directory"));

                return wxEmptyString;
            }
            else
            {
                // buffer was too small, retry with a larger one
                len *= 2;
            }
        }
        //else: ok
    } while ( !ok );

    return dir;
}
Example #26
0
bool wxDynamicLibrary::Load(const wxString& libnameOrig, int flags)
{
    wxASSERT_MSG(m_handle == 0, wxT("Library already loaded."));

    // add the proper extension for the DLL ourselves unless told not to
    wxString libname = libnameOrig;
    if ( !(flags & wxDL_VERBATIM) )
    {
        // and also check that the libname doesn't already have it
        wxString ext;
        wxFileName::SplitPath(libname, NULL, NULL, &ext);
        if ( ext.empty() )
        {
            libname += GetDllExt(wxDL_MODULE);
        }
    }

    // different ways to load a shared library
    //
    // FIXME: should go to the platform-specific files!
#if defined(__WXPM__) || defined(__EMX__)
    char err[256] = "";
    DosLoadModule(err, sizeof(err), libname.c_str(), &m_handle);
#else // this should be the only remaining branch eventually
    m_handle = RawLoad(libname, flags);
#endif

    if ( m_handle == 0 && !(flags & wxDL_QUIET) )
    {
#ifdef wxHAVE_DYNLIB_ERROR
        Error();
#else
        wxLogSysError(_("Failed to load shared library '%s'"), libname.c_str());
#endif
    }

    return IsLoaded();
}
Example #27
0
bool wxFSWatcherImplMSW::DoSetUpWatch(wxFSWatchEntryMSW& watch)
{
    BOOL bWatchSubtree wxDUMMY_INITIALIZE(FALSE);

    switch ( watch.GetType() )
    {
        case wxFSWPath_File:
            wxLogError(_("Monitoring individual files for changes is not "
                         "supported currently."));
            return false;

        case wxFSWPath_Dir:
            bWatchSubtree = FALSE;
            break;

        case wxFSWPath_Tree:
            bWatchSubtree = TRUE;
            break;

        case wxFSWPath_None:
            wxFAIL_MSG( "Invalid watch type." );
            return false;
    }

    int flags = Watcher2NativeFlags(watch.GetFlags());
    int ret = ReadDirectoryChangesW(watch.GetHandle(), watch.GetBuffer(),
                                    wxFSWatchEntryMSW::BUFFER_SIZE,
                                    bWatchSubtree,
                                    flags, NULL,
                                    watch.GetOverlapped(), NULL);
    if (!ret)
    {
        wxLogSysError(_("Unable to set up watch for '%s'"),
                        watch.GetPath());
    }

    return ret != 0;
}
Example #28
0
size_t wxPipeOutputStream::OnSysWrite(const void *buffer, size_t size)
{
    // We need to suppress error logging here, because on writing to a pipe
    // which is full, wxFile::Write reports a system error. However, this is
    // not an extraordinary situation, and it should not be reported to the
    // user (but if really needed, the program can recognize it by checking
    // whether LastRead() == 0.) Other errors will be reported below.
    size_t ret;
    {
        wxLogNull logNo;
        ret = m_file->Write(buffer, size);
    }

    switch ( m_file->GetLastError() )
    {
       // pipe is full
#ifdef EAGAIN
       case EAGAIN:
#endif
#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
       case EWOULDBLOCK:
#endif
           // do not treat it as an error
           m_file->ClearLastError();
           wxFALLTHROUGH;

       // no error
       case 0:
           break;

       // some real error
       default:
           wxLogSysError(_("Can't write to child process's stdin"));
           m_lasterror = wxSTREAM_WRITE_ERROR;
    }

    return ret;
}
Example #29
0
bool wxRarInputStream::OpenNextFile()
{
	RARHeaderData hd;

    int nError;

    if ((nError = RARReadHeader(m_hRar, &hd)) != 0)
    {
        //wxMessageBox(wxString::Format(_T("AHH  %ld"), nError));
		if (nError != ERAR_END_ARCHIVE) {
			wxLogSysError(wxString::Format(_("Error : %ld"), nError));
		}
        return false;
	}

	m_Info.szName = wxStringFromBBString(bbStringFromCString(hd.FileName));
	m_Info.szComment = hd.CmtBuf;
	m_Info.dwUncompressedSize = hd.UnpSize;
	m_Info.dwCompressedSize = hd.PackSize;
	m_Info.dwTime = hd.FileTime;
	
	return true;
}
Example #30
0
bool wxAppConsole::SetSignalHandler(int signal, SignalHandler handler)
{
    const bool install = (SignalHandler_t)handler != SIG_DFL &&
                         (SignalHandler_t)handler != SIG_IGN;

    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = (SignalHandler_t)&wxAppConsole::HandleSignal;
    sa.sa_flags = SA_RESTART;
    int res = sigaction(signal, &sa, 0);
    if ( res != 0 )
    {
        wxLogSysError(_("Failed to install signal handler"));
        return false;
    }

    if ( install )
        m_signalHandlerHash[signal] = handler;
    else
        m_signalHandlerHash.erase(signal);

    return true;
}