コード例 #1
0
ファイル: ImportOGG.cpp プロジェクト: Avi2011class/audacity
int OggImportFileHandle::Import(TrackFactory *trackFactory, TrackHolders &outTracks,
                                Tags *tags)
{
   outTracks.clear();

   wxASSERT(mFile->IsOpened());

   CreateProgress();

   //Number of streams used may be less than mVorbisFile->links,
   //but this way bitstream matches array index.
   mChannels.resize(mVorbisFile->links);

   int i = -1;
   for (auto &link: mChannels)
   {
      ++i;

      //Stream is not used
      if (mStreamUsage[i] == 0)
      {
         //This is just a padding to keep bitstream number and
         //array indices matched.
         continue;
      }

      vorbis_info *vi = ov_info(mVorbisFile, i);

      link.resize(vi->channels);

      int c = - 1;
      for (auto &channel : link) {
         ++c;

         channel = trackFactory->NewWaveTrack(mFormat, vi->rate);

         if (vi->channels == 2) {
            switch (c) {
         case 0:
            channel->SetChannel(Track::LeftChannel);
            channel->SetLinked(true);
            break;
         case 1:
            channel->SetChannel(Track::RightChannel);
            break;
            }
         }
         else {
            channel->SetChannel(Track::MonoChannel);
         }
      }
   }

/* The number of bytes to get from the codec in each run */
#define CODEC_TRANSFER_SIZE 4096

/* The number of samples to read between calls to the callback.
 * Balance between responsiveness of the GUI and throughput of import. */
#define SAMPLES_PER_CALLBACK 100000

   short *mainBuffer = new short[CODEC_TRANSFER_SIZE];

   /* determine endianness (clever trick courtesy of Nicholas Devillard,
    * (http://www.eso.org/~ndevilla/endian/) */
   int testvar = 1, endian;
   if(*(char *)&testvar)
      endian = 0;  // little endian
   else
      endian = 1;  // big endian

   /* number of samples currently in each channel's buffer */
   int updateResult = eProgressSuccess;
   long bytesRead = 0;
   long samplesRead = 0;
   int bitstream = 0;
   int samplesSinceLastCallback = 0;

   // You would think that the stream would already be seeked to 0, and
   // indeed it is if the file is legit.  But I had several ogg files on
   // my hard drive that have malformed headers, and this added call
   // causes them to be read correctly.  Otherwise they have lots of
   // zeros inserted at the beginning
   ov_pcm_seek(mVorbisFile, 0);

   do {
      /* get data from the decoder */
      bytesRead = ov_read(mVorbisFile, (char *) mainBuffer,
                          CODEC_TRANSFER_SIZE,
                          endian,
                          2,    // word length (2 for 16 bit samples)
                          1,    // signed
                          &bitstream);

      if (bytesRead == OV_HOLE) {
         wxFileName ff(mFilename);
         wxLogError(wxT("Ogg Vorbis importer: file %s is malformed, ov_read() reported a hole"),
                    ff.GetFullName().c_str());
         /* http://lists.xiph.org/pipermail/vorbis-dev/2001-February/003223.html
          * is the justification for doing this - best effort for malformed file,
          * hence the message.
          */
         continue;
      } else if (bytesRead < 0) {
         /* Malformed Ogg Vorbis file. */
         /* TODO: Return some sort of meaningful error. */
         wxLogError(wxT("Ogg Vorbis importer: ov_read() returned error %i"),
                    bytesRead);
         break;
      }

      samplesRead = bytesRead / mVorbisFile->vi[bitstream].channels / sizeof(short);

      /* give the data to the wavetracks */
      auto iter = mChannels.begin();
      std::advance(iter, bitstream);
      if (mStreamUsage[bitstream] != 0)
      {
         auto iter2 = iter->begin();
         for (int c = 0; c < mVorbisFile->vi[bitstream].channels; ++iter2, ++c)
            iter2->get()->Append((char *)(mainBuffer + c),
            int16Sample,
            samplesRead,
            mVorbisFile->vi[bitstream].channels);
      }

      samplesSinceLastCallback += samplesRead;
      if (samplesSinceLastCallback > SAMPLES_PER_CALLBACK) {
          updateResult = mProgress->Update(ov_time_tell(mVorbisFile),
                                         ov_time_total(mVorbisFile, bitstream));
          samplesSinceLastCallback -= SAMPLES_PER_CALLBACK;

      }
   } while (updateResult == eProgressSuccess && bytesRead != 0);

   delete[]mainBuffer;

   int res = updateResult;
   if (bytesRead < 0)
     res = eProgressFailed;

   if (res == eProgressFailed || res == eProgressCancelled) {
      return res;
   }

   for (auto &link : mChannels)
   {
      for (auto &channel : link) {
         channel->Flush();
         outTracks.push_back(std::move(channel));
      }
   }

   //\todo { Extract comments from each stream? }
   if (mVorbisFile->vc[0].comments > 0) {
      tags->Clear();
      for (int c = 0; c < mVorbisFile->vc[0].comments; c++) {
         wxString comment = UTF8CTOWX(mVorbisFile->vc[0].user_comments[c]);
         wxString name = comment.BeforeFirst(wxT('='));
         wxString value = comment.AfterFirst(wxT('='));
         if (name.Upper() == wxT("DATE") && !tags->HasTag(TAG_YEAR)) {
            long val;
            if (value.Length() == 4 && value.ToLong(&val)) {
               name = TAG_YEAR;
            }
         }
         tags->SetTag(name, value);
      }
   }

   return res;
}
コード例 #2
0
bool wxTIFFHandler::LoadFile( wxImage *image, wxInputStream& stream, bool verbose, int index )
{
    if (index == -1)
        index = 0;

    image->Destroy();

    TIFF *tif = TIFFwxOpen( stream, "image", "r" );

    if (!tif)
    {
        if (verbose)
            wxLogError( _("TIFF: Error loading image.") );

        return false;
    }

    if (!TIFFSetDirectory( tif, (tdir_t)index ))
    {
        if (verbose)
            wxLogError( _("Invalid TIFF image index.") );

        TIFFClose( tif );

        return false;
    }

    uint32 w, h;
    uint32 npixels;
    uint32 *raster;

    TIFFGetField( tif, TIFFTAG_IMAGEWIDTH, &w );
    TIFFGetField( tif, TIFFTAG_IMAGELENGTH, &h );

    npixels = w * h;

    raster = (uint32*) _TIFFmalloc( npixels * sizeof(uint32) );

    if (!raster)
    {
        if (verbose)
            wxLogError( _("TIFF: Couldn't allocate memory.") );

        TIFFClose( tif );

        return false;
    }

    image->Create( (int)w, (int)h );
    if (!image->Ok())
    {
        if (verbose)
            wxLogError( _("TIFF: Couldn't allocate memory.") );

        _TIFFfree( raster );
        TIFFClose( tif );

        return false;
    }

    if (!TIFFReadRGBAImage( tif, w, h, raster, 0 ))
    {
        if (verbose)
            wxLogError( _("TIFF: Error reading image.") );

        _TIFFfree( raster );
        image->Destroy();
        TIFFClose( tif );

        return false;
    }

    bool hasmask = false;

    unsigned char *ptr = image->GetData();
    ptr += w*3*(h-1);
    uint32 pos = 0;

    for (uint32 i = 0; i < h; i++)
    {
        for (uint32 j = 0; j < w; j++)
        {
            unsigned char alpha = (unsigned char)TIFFGetA(raster[pos]);
            if (alpha < 127)
            {
                hasmask = true;
                ptr[0] = image->GetMaskRed();
                ptr++;
                ptr[0] = image->GetMaskGreen();
                ptr++;
                ptr[0] = image->GetMaskBlue();
                ptr++;
            }
            else
            {
                ptr[0] = (unsigned char)TIFFGetR(raster[pos]);
                ptr++;
                ptr[0] = (unsigned char)TIFFGetG(raster[pos]);
                ptr++;
                ptr[0] = (unsigned char)TIFFGetB(raster[pos]);
                ptr++;
            }
            pos++;
        }
        ptr -= 2*w*3; // subtract line we just added plus one line
    }

    _TIFFfree( raster );

    TIFFClose( tif );

    image->SetMask( hasmask );

    return true;
}
コード例 #3
0
void
EventWorker::OnSocketEvent(wxSocketEvent& pEvent) {
    switch(pEvent.GetSocketEvent()) {
        case wxSOCKET_INPUT:
            //wxLogDebug(wxT("EventWorker: INPUT"));
            do {
                if (m_readed == m_insize)
                    return; //event already posted
                m_clientSocket->Read(m_inbuf + m_readed, m_insize - m_readed);
                if (m_clientSocket->Error())
                {
                    if (m_clientSocket->LastError() != wxSOCKET_WOULDBLOCK)
                    {
                        wxLogError(wxT("%s: read error"),CreateIdent(m_localaddr).c_str());
                        SendEvent(true);
                    }
                }

                m_readed += m_clientSocket->LastCount();
                //wxLogDebug(wxT("EventWorker: readed %d bytes, %d bytes to do"),m_clientSocket->LastCount(), m_insize - m_readed);
                if (m_readed == m_insize)
                {
                    if (!memcmp(m_inbuf,m_outbuf,m_insize)) {
                        wxLogError(wxT("%s: data mismatch"),CreateIdent(m_localaddr).c_str());
                        SendEvent(true);
                    }
                    m_currentType = WorkerEvent::DISCONNECTING;
                    wxLogDebug(wxT("%s: DISCONNECTING"),CreateIdent(m_localaddr).c_str());
                    SendEvent(false);

                    //wxLogDebug(wxT("EventWorker %p closing"),this);
                    m_clientSocket->Close();

                    m_currentType = WorkerEvent::DONE;
                    wxLogDebug(wxT("%s: DONE"),CreateIdent(m_localaddr).c_str());
                    SendEvent(false);
                }
            } while (!m_clientSocket->Error());
        break;
        case wxSOCKET_OUTPUT:
            //wxLogDebug(wxT("EventWorker: OUTPUT"));
            do {
                if (m_written == m_outsize)
                    return;
                if (m_written == 0)
                {
                    m_currentType = WorkerEvent::SENDING;
                    wxLogDebug(wxT("%s: SENDING"),CreateIdent(m_localaddr).c_str());
                }
                m_clientSocket->Write(m_outbuf + m_written, m_outsize - m_written);
                if (m_clientSocket->Error())
                {
                    if (m_clientSocket->LastError() != wxSOCKET_WOULDBLOCK) {
                        wxLogError(wxT("%s: Write error"),CreateIdent(m_localaddr).c_str());
                        SendEvent(true);
                    }
                }
                m_written += m_clientSocket->LastCount();
                if (m_written != m_outsize)
                {
                    //wxLogDebug(wxT("EventWorker: written %d bytes, %d bytes to do"),m_clientSocket->LastCount(),m_outsize - m_written);
                }
                else
                {
                    //wxLogDebug(wxT("EventWorker %p SENDING->RECEIVING"),this);
                    m_currentType = WorkerEvent::RECEIVING;
                    wxLogDebug(wxT("%s: RECEIVING"),CreateIdent(m_localaddr).c_str());
                    SendEvent(false);
                }
            } while(!m_clientSocket->Error());
        break;
        case wxSOCKET_CONNECTION:
        {
            //wxLogMessage(wxT("EventWorker: got connection"));
            wxLogMessage(wxT("%s: starting writing message (2 bytes for signature and %d bytes of data to write)"),CreateIdent(m_localaddr).c_str(),m_outsize-2);
            if (!m_clientSocket->GetLocal(m_localaddr))
            {
                wxLogError(_("Cannot get peer data for socket %p"),m_clientSocket);
            }
            m_currentType = WorkerEvent::SENDING;
            wxLogDebug(wxT("%s: CONNECTING"),CreateIdent(m_localaddr).c_str());
            SendEvent(false);
        }
        break;
        case wxSOCKET_LOST:
        {
            wxLogError(_("%s: connection lost"),CreateIdent(m_localaddr).c_str());
            SendEvent(true);
        }
        break;
    }
}
コード例 #4
0
void dlgSelectConnection::OnChangeServer(wxCommandEvent& ev)
{
    int item;
    wxString olddatabase, oldusername;
    
	if (!GetServer())
		return;

    // Keep old value for these comboboxes so that we can restore them if needed
    olddatabase = cbDatabase->GetValue();
    oldusername = cbUsername->GetValue();
    
    // Clear the comboboxes
    cbDatabase->Clear();
    cbUsername->Clear();
    cbRolename->Clear();

    int sel=cbServer->GetCurrentSelection();
    if (sel >= 0)
    {
        remoteServer = (pgServer*)cbServer->GetClientData(sel);

        if (!remoteServer->GetConnected())
        {
            remoteServer->Connect(mainForm, remoteServer->GetStorePwd());
            if (!remoteServer->GetConnected())
            {
                wxLogError(wxT("%s"), remoteServer->GetLastError().c_str());
                return;
            }
        }
        if (remoteServer->GetConnected())
        {
            pgSetIterator set1(remoteServer->GetConnection(), 
                wxT("SELECT DISTINCT datname\n")
                wxT("  FROM pg_database db\n")
                wxT(" WHERE datallowconn ORDER BY datname"));

            item = 0;
            while(set1.RowsLeft())
            {
                cbDatabase->Append(set1.GetVal(wxT("datname")));
                if (set1.GetVal(wxT("datname")) == olddatabase)
                    item = cbDatabase->GetCount() - 1;
            }

            if (cbDatabase->GetCount())
                cbDatabase->SetSelection(item);

            pgSetIterator set2(remoteServer->GetConnection(), 
                wxT("SELECT DISTINCT usename\n")
                wxT("FROM pg_user db\n")
                wxT("ORDER BY usename"));

            item = 0;
            while(set2.RowsLeft())
            {
                cbUsername->Append(set2.GetVal(wxT("usename")));
                if (set2.GetVal(wxT("usename")) == oldusername)
                    item = cbDatabase->GetCount() - 1;
            }

            if (cbUsername->GetCount())
                cbUsername->SetSelection(item);

            if (remoteServer->GetConnection()->BackendMinimumVersion(8, 1))
            {
                pgSetIterator set3(remoteServer->GetConnection(),
                    wxT("SELECT DISTINCT rolname\n")
                    wxT("FROM pg_roles db\n")
                    wxT("ORDER BY rolname"));

                cbRolename->Append(wxEmptyString);

                while(set3.RowsLeft())
                    cbRolename->Append(set3.GetVal(wxT("rolname")));

                cbRolename->Enable(true);
            }
            else
                cbRolename->Disable();

            cbRolename->SetValue(wxEmptyString);
        }

    }
    OnChangeDatabase(ev);
}
コード例 #5
0
ファイル: clipbrd.cpp プロジェクト: chromylei/third_party
void *wxGetClipboardData(wxDataFormat dataFormat, long *len)
{
    void *retval = NULL;

    switch ( dataFormat )
    {
#ifndef __WXWINCE__
        case wxDF_BITMAP:
            {
                BITMAP bm;
                HBITMAP hBitmap = (HBITMAP) GetClipboardData(CF_BITMAP);
                if (!hBitmap)
                    break;

                HDC hdcMem = CreateCompatibleDC((HDC) NULL);
                HDC hdcSrc = CreateCompatibleDC((HDC) NULL);

                HBITMAP old = (HBITMAP) ::SelectObject(hdcSrc, hBitmap);
                GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);

                HBITMAP hNewBitmap = CreateBitmapIndirect(&bm);

                if (!hNewBitmap)
                {
                    SelectObject(hdcSrc, old);
                    DeleteDC(hdcMem);
                    DeleteDC(hdcSrc);
                    break;
                }

                HBITMAP old1 = (HBITMAP) SelectObject(hdcMem, hNewBitmap);
                BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight,
                       hdcSrc, 0, 0, SRCCOPY);

                // Select new bitmap out of memory DC
                SelectObject(hdcMem, old1);

                // Clean up
                SelectObject(hdcSrc, old);
                DeleteDC(hdcSrc);
                DeleteDC(hdcMem);

                // Create and return a new wxBitmap
                wxBitmap *wxBM = new wxBitmap;
                wxBM->SetHBITMAP((WXHBITMAP) hNewBitmap);
                wxBM->SetWidth(bm.bmWidth);
                wxBM->SetHeight(bm.bmHeight);
                wxBM->SetDepth(bm.bmPlanes);
                retval = wxBM;
                break;
            }
#endif
        case wxDF_METAFILE:
        case CF_SYLK:
        case CF_DIF:
        case CF_TIFF:
        case CF_PALETTE:
        case wxDF_DIB:
            wxLogError(_("Unsupported clipboard format."));
            return NULL;

        case wxDF_OEMTEXT:
            dataFormat = wxDF_TEXT;
            // fall through

        case wxDF_TEXT:
            {
                HANDLE hGlobalMemory = ::GetClipboardData(dataFormat);
                if (!hGlobalMemory)
                    break;

                DWORD hsize = ::GlobalSize(hGlobalMemory);
                if (len)
                    *len = hsize;

                char *s = new char[hsize];
                if (!s)
                    break;

                LPSTR lpGlobalMemory = (LPSTR) GlobalLock(hGlobalMemory);

                memcpy(s, lpGlobalMemory, hsize);

                GlobalUnlock(hGlobalMemory);

                retval = s;
                break;
            }

        default:
            {
                HANDLE hGlobalMemory = ::GetClipboardData(dataFormat);
                if ( !hGlobalMemory )
                    break;

                DWORD size = ::GlobalSize(hGlobalMemory);
                if ( len )
                    *len = size;

                void *buf = malloc(size);
                if ( !buf )
                    break;

                LPSTR lpGlobalMemory = (LPSTR) GlobalLock(hGlobalMemory);

                memcpy(buf, lpGlobalMemory, size);

                GlobalUnlock(hGlobalMemory);

                retval = buf;
                break;
            }
    }

    if ( !retval )
    {
        wxLogSysError(_("Failed to retrieve data from the clipboard."));
    }

    return retval;
}
コード例 #6
0
// load the mxf file format
bool wxMXFHandler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)
{
	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *opjimage = NULL;
	unsigned char *src = NULL;
    unsigned char *ptr;
	int file_length, j2k_point, j2k_len;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */

	// destroy the image
    image->Destroy();

	/* handle to a decompressor */
	opj_dinfo_t* dinfo = NULL;	
	opj_cio_t *cio = NULL;

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = mxf_error_callback;
	event_mgr.warning_handler = mxf_warning_callback;
	event_mgr.info_handler = mxf_info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* prepare parameters */
	strncpy(parameters.infile, "", sizeof(parameters.infile)-1);
	strncpy(parameters.outfile, "", sizeof(parameters.outfile)-1);
	parameters.decod_format = J2K_CFMT;
	parameters.cod_format = BMP_DFMT;
	if (m_reducefactor)
		parameters.cp_reduce = m_reducefactor;
	if (m_qualitylayers)
		parameters.cp_layer = m_qualitylayers;
	/*if (n_components)
		parameters. = n_components;*/

	/* JPWL only */
#ifdef USE_JPWL
	parameters.jpwl_exp_comps = m_expcomps;
	parameters.jpwl_max_tiles = m_maxtiles;
	parameters.jpwl_correct = m_enablejpwl;
#endif /* USE_JPWL */

	/* get a decoder handle */
	dinfo = opj_create_decompress(CODEC_J2K);

	/* find length of the stream */
	stream.SeekI(0, wxFromEnd);
	file_length = (int) stream.TellI();

	/* search for the m_framenum codestream position and length  */
	//jp2c_point = searchjp2c(stream, file_length, m_framenum);
	//jp2c_len = searchjp2c(stream, file_length, m_framenum);
	j2k_point = 0;
	j2k_len = 10;

	// malloc memory source
    src = (unsigned char *) malloc(j2k_len);

	// copy the jp2c
	stream.SeekI(j2k_point, wxFromStart);
	stream.Read(src, j2k_len);

	/* catch events using our callbacks and give a local context */
	opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

	/* setup the decoder decoding parameters using user parameters */
	opj_setup_decoder(dinfo, &parameters);

	/* open a byte stream */
	cio = opj_cio_open((opj_common_ptr)dinfo, src, j2k_len);

	/* decode the stream and fill the image structure */
	opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);
	if (!opjimage) {
		wxMutexGuiEnter();
		wxLogError(wxT("MXF: failed to decode image!"));
		wxMutexGuiLeave();
		opj_destroy_decompress(dinfo);
		opj_cio_close(cio);
		free(src);
		return false;
	}

	/* close the byte stream */
	opj_cio_close(cio);

	/* common rendering method */
#include "imagjpeg2000.cpp"

    wxMutexGuiEnter();
    wxLogMessage(wxT("MXF: image loaded."));
    wxMutexGuiLeave();

	/* close openjpeg structs */
	opj_destroy_decompress(dinfo);
	opj_image_destroy(opjimage);
	free(src);

	if (!image->Ok())
		return false;
	else
		return true;

}
コード例 #7
0
// same as AddPage() but does it at given position
bool wxNotebook::InsertPage(size_t nPage,
                            wxNotebookPage *pPage,
                            const wxString& strText,
                            bool bSelect,
                            int imageId)
{
    wxCHECK_MSG( pPage != NULL, false, wxT("NULL page in wxNotebook::InsertPage") );
    wxCHECK_MSG( IS_VALID_PAGE(nPage) || nPage == GetPageCount(), false,
                 wxT("invalid index in wxNotebook::InsertPage") );

    wxASSERT_MSG( pPage->GetParent() == this,
                    wxT("notebook pages must have notebook as parent") );

    // add a new tab to the control
    // ----------------------------

    // init all fields to 0
    TC_ITEM tcItem;
    wxZeroMemory(tcItem);

    // set the image, if any
    if ( imageId != -1 )
    {
        tcItem.mask |= TCIF_IMAGE;
        tcItem.iImage  = imageId;
    }

    // and the text
    if ( !strText.empty() )
    {
        tcItem.mask |= TCIF_TEXT;
        tcItem.pszText = (wxChar *)strText.wx_str(); // const_cast
    }

    // hide the page: unless it is selected, it shouldn't be shown (and if it
    // is selected it will be shown later)
    HWND hwnd = GetWinHwnd(pPage);
    SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_VISIBLE);

    // this updates internal flag too -- otherwise it would get out of sync
    // with the real state
    pPage->Show(false);


    // fit the notebook page to the tab control's display area: this should be
    // done before adding it to the notebook or TabCtrl_InsertItem() will
    // change the notebooks size itself!
    AdjustPageSize(pPage);

    // finally do insert it
    if ( TabCtrl_InsertItem(GetHwnd(), nPage, &tcItem) == -1 )
    {
        wxLogError(wxT("Can't create the notebook page '%s'."), strText.c_str());

        return false;
    }

    // need to update the bg brush when the first page is added
    // so the first panel gets the correct themed background
    if ( m_pages.empty() )
    {
#if wxUSE_UXTHEME
        UpdateBgBrush();
#endif // wxUSE_UXTHEME
    }

    // succeeded: save the pointer to the page
    m_pages.Insert(pPage, nPage);

    // also ensure that the notebook background is used for its pages by making
    // them transparent: this ensures that MSWGetBgBrush() queries the notebook
    // for the background brush to be used for erasing them
    if ( wxPanel *panel = wxDynamicCast(pPage, wxPanel) )
    {
        panel->MSWSetTransparentBackground();
    }

    // we may need to adjust the size again if the notebook size changed:
    // normally this only happens for the first page we add (the tabs which
    // hadn't been there before are now shown) but for a multiline notebook it
    // can happen for any page at all as a new row could have been started
    if ( m_pages.GetCount() == 1 || HasFlag(wxNB_MULTILINE) )
    {
        AdjustPageSize(pPage);
    }

    // now deal with the selection
    // ---------------------------

    // if the inserted page is before the selected one, we must update the
    // index of the selected page
    if ( int(nPage) <= m_nSelection )
    {
        // one extra page added
        m_nSelection++;
    }

    // some page should be selected: either this one or the first one if there
    // is still no selection
    int selNew = wxNOT_FOUND;
    if ( bSelect )
        selNew = nPage;
    else if ( m_nSelection == wxNOT_FOUND )
        selNew = 0;

    if ( selNew != wxNOT_FOUND )
        SetSelection(selNew);

    InvalidateBestSize();

    return true;
}
コード例 #8
0
ファイル: FSOExecutable.cpp プロジェクト: asarium/wxlauncher
FSOExecutable FSOExecutable::GetBinaryVersion(wxString binaryname) {
	wxLogDebug(_T("Making version struct for the executable '%s'"), binaryname.c_str());
	FSOExecutable ver;
	wxStringTokenizer tok(binaryname, _T("_.- ()[]/"));
	ver.executablename = binaryname;

	if ( !tok.HasMoreTokens() ) {
		wxLogError(
			_T("Did not find initial 'fs2' or 'fred2' token in executable '%s'"),
				binaryname.c_str());
		return ver;
	}
	wxString first(tok.GetNextToken());
	if ( tok.HasMoreTokens() && (!first.CmpNoCase(_T("fred2")) || !first.CmpNoCase(_T("fs2"))) ) {
		wxString second(tok.GetNextToken());
		if ( !second.CmpNoCase(_T("open")) ) {
			if ( !first.CmpNoCase(_T("fs2")) ) {
				ver.binaryname = _T("FS2 Open");
			} else {
				ver.binaryname = _T("FRED2 Open");
			}
		} else {
			wxLogWarning(_T("was expecting 'open'; got %s in executable %s"),
				second.c_str(), binaryname.c_str());
			return ver;
		}
	} else {
		wxLogWarning(_T("executable name '%s' too short"), binaryname.c_str());
		return ver;
	}

	while ( tok.HasMoreTokens() ) {
		wxString token = tok.GetNextToken();
		wxString temp;
		long tempVersion;

		if (token.IsEmpty()) { // can happen in OS X nightly debug builds
			// do nothing
		} else if ( !token.CmpNoCase(_T("exe")) ) {
			; // do nothing
#if IS_APPLE
		} else if ( !token.CmpNoCase(_T("app")) ) {
			break; // we've reached the end of the app name
#endif
		} else if ( token.ToLong(&tempVersion) && token.size() == 8 ) {
			// must be a date from a nightly build; add it to the string
			if (!ver.string.IsEmpty()) {
				ver.string += _T(" ");
			}
			// add it in YYYY-MM-DD format
			ver.string += token.Mid(0, 4);
			ver.string += _T("-");
			ver.string += token.Mid(4, 2);
			ver.string += _T("-");
			ver.string += token.Mid(6, 2);
		} else if ( token.ToLong(&tempVersion) && ver.antipodes && ver.antNumber == 0) {
			// must be antipodes number
			if ( tempVersion > 0 ) {
				ver.antNumber = (int)tempVersion;
			} else {
				wxLogWarning(
					_T("antipodes number out of range (%ld) in executable %s"),
						tempVersion, binaryname.c_str());
			}
		} else if ( token.ToLong(&tempVersion) && ver.major == 0 ) {
			// must be major version number
			if ( tempVersion < 1000 && tempVersion > 0 ) {
				ver.major = (int)tempVersion;
			} else {
				wxLogWarning(
					_T("major version number out of range (%ld) in executable %s"),
						tempVersion, binaryname.c_str());
			}
		} else if ( token.ToLong(&tempVersion) && ver.minor == 0 ) {
			// must be minor version number
			if ( tempVersion < 1000 && tempVersion >= 0 ) {
				ver.minor = (int)tempVersion;
			} else {
				wxLogWarning(
					_T("minor version number out of range (%ld) in executable %s"),
						tempVersion, binaryname.c_str());
			}
		} else if ( token.ToLong(&tempVersion) && ver.revision == 0) {
			// must be revision version number
			if ( tempVersion < 1000 && tempVersion >= 0 ) {
				ver.revision = (int)tempVersion;
			} else {
				wxLogWarning(
					_T("Revision version number out of range (%ld) in executable %s"),
						tempVersion, binaryname.c_str());
			}
		} else if ( !token.CmpNoCase(_T("d")) || !token.CmpNoCase(_T("debug")) ) {
			ver.debug = true;
		} else if ( token.Lower().EndsWith(_T("d"), &temp) ) {
			if ( temp.ToLong(&tempVersion) ) {
				// is the revision version number
				if ( tempVersion < 1000 && tempVersion >= 0 ) {
					ver.revision = (int)tempVersion;
					ver.debug = true;
				} else {
					wxLogWarning(
						_T("Revision version number out of range (%ld) in executable %s"),
							tempVersion, binaryname.c_str());
				}
			} else {
				wxLogWarning(
					_T("Token ending in 'd' is not a number (%s) in executable %s"),
						token.c_str(), binaryname.c_str());
				ver.string += wxString::Format(ver.string.IsEmpty() ? _T("%s") : _T(" %s") , token.c_str());
			}
		} else if ( token.Lower().EndsWith(_T("r"), &temp) ) {
			if (temp.IsEmpty()) {
				// do nothing, the 'r' wasn't preceded by a number
			} else if ( temp.ToLong(&tempVersion) ) {
				// is the revision version number
				if ( tempVersion < 1000 && tempVersion >= 0 ) {
					ver.revision = (int)tempVersion;
					ver.debug = false;
				} else {
					wxLogWarning(
						_T("Revision version number out of range (%ld) in executable %s"),
							tempVersion, binaryname.c_str());
				}
			} else {
				wxLogWarning(
					_T("Token ending in 'r' is not a number (%s) in executable %s"),
						token.c_str(), binaryname.c_str());
				ver.string += wxString::Format(ver.string.IsEmpty() ? _T("%s") : _T(" %s"), token.c_str());
			}
		} else if ( token.StartsWith(_T("r"), &temp) && temp.ToLong(&tempVersion) ) {
			// must be a revision number from SirKnightly's builds
			if ( tempVersion > 0 ) {
				ver.build = (int)tempVersion;
			} else {
				wxLogWarning(
					_T("SirKnightly build number out of range (%ld) in executable %s"),
						tempVersion, binaryname.c_str());
			}
		} else if ( !token.CmpNoCase(_T("ant")) ) {
			ver.antipodes = true;
		} else if ( token.Lower().StartsWith(_T("ant"), &temp) && !ver.antipodes ) {
			ver.antipodes = true;

			// in case the token is of the format, e.g., "Ant8"
			long antNumber;
			if (temp.ToLong(&antNumber)) {
				if (antNumber > 0) {
					ver.antNumber = antNumber;
				} else {
					wxLogWarning(_T("Invalid antipodes number %ld in executable %s"),
						antNumber, binaryname.c_str());
				}
			}
		} else if ( !token.CmpNoCase(_T("avx")) ) {
			ver.sse = 3;
		} else if ( !token.CmpNoCase(_T("sse2")) ) {
			ver.sse = 2;
		} else if ( !token.CmpNoCase(_T("sse")) ) {
			if (ver.string.Lower().EndsWith(_T("no"))) { // probably NO SSE
				ver.sse = -1;
				
				const int lastSpaceIndex = ver.string.Find(_T(' '), true);
				
				if (lastSpaceIndex == wxNOT_FOUND) {
					wxASSERT(ver.string.Lower() == _T("no"));
					ver.string = wxEmptyString;
				} else {
					ver.string = ver.string.Mid(0, lastSpaceIndex);
				}
			} else {
				ver.sse = 1;
			}
		} else if ( !token.CmpNoCase(_T("inf")) || !token.CmpNoCase(_T("inferno"))) {
			ver.inferno = true;
		} else {
			if (!ver.string.IsEmpty()) {
				ver.string += _T(" ");
			}
			ver.string += token;
		}
	}
	
	return ver;
}
コード例 #9
0
bool CDPlusAuthenticator::authenticate(const wxString& callsign, const wxString& hostname, unsigned int port, unsigned char id, bool writeToCache)
{
	CTCPReaderWriterClient socket(hostname, port, m_address);

	bool ret = socket.open();
	if (!ret)
		return false;

	unsigned char* buffer = new unsigned char[600U];
	::memset(buffer, ' ', 56U);

	buffer[0U] = 0x38U;
	buffer[1U] = 0xC0U;
	buffer[2U] = 0x01U;
	buffer[3U] = 0x00U;

	for (unsigned int i = 0U; i < callsign.Len(); i++)
		buffer[i + 4U] = callsign.GetChar(i);

	buffer[12U] = 'D';
	buffer[13U] = 'V';
	buffer[14U] = '0';
	buffer[15U] = '1';
	buffer[16U] = '9';
	buffer[17U] = '9';
	buffer[18U] = '9';
	buffer[19U] = '9';

	buffer[28U] = 'W';
	buffer[29U] = '7';
	buffer[30U] = 'I';
	buffer[31U] = 'B';
	buffer[32U] = id;

	buffer[40U] = 'D';
	buffer[41U] = 'H';
	buffer[42U] = 'S';
	buffer[43U] = '0';
	buffer[44U] = '2';
	buffer[45U] = '5';
	buffer[46U] = '7';

	ret = socket.write(buffer, 56U);
	if (!ret) {
		socket.close();
		delete[] buffer;
		return false;
	}

	ret = read(socket, buffer + 0U, 2U);

	while (ret) {
		unsigned int len = (buffer[1U] & 0x0FU) * 256U + buffer[0U];

		// Ensure that we get exactly len - 2U bytes from the TCP stream
		ret = read(socket, buffer + 2U, len - 2U);
		if (!ret) {
			wxLogError(wxT("Short read from %s:%u"), hostname.c_str(), port);
			break;
		}

		if ((buffer[1U] & 0xC0U) != 0xC0U || buffer[2U] != 0x01U) {
			wxLogError(wxT("Invalid packet received from %s:%u"), hostname.c_str(), port);
			CUtils::dump(wxT("Details:"), buffer, len);
			ret = read(socket, buffer + 0U, 2U);
			continue;
		}
	
		for (unsigned int i = 8U; i < len; i += 26U) {
			wxString address = wxString((char*)(buffer + i + 0U),  wxConvLocal);
			wxString    name = wxString((char*)(buffer + i + 16U), wxConvLocal);

			address.Trim();
			name.Trim();

			// Get the active flag
			bool active = (buffer[i + 25U] & 0x80U) == 0x80U;

			// An empty name or IP address or an inactive gateway/reflector is not written out
			if (address.Len() > 0U && name.Len() > 0U && !name.Left(3U).IsSameAs(wxT("XRF")) && active && writeToCache){
				if (name.Left(3U).IsSameAs(wxT("REF")))
					wxLogMessage(wxT("D-Plus: %s\t%s"), name.c_str(), address.c_str());

				name.Append(wxT("        "));
				name.Truncate(LONG_CALLSIGN_LENGTH - 1U);
				name.Append(wxT("G"));
				m_cache->updateGateway(name, address, DP_DPLUS, false, true);
			}
		}

		ret = read(socket, buffer + 0U, 2U);
	}

	wxLogMessage(wxT("Registered with %s using callsign %s"), hostname.c_str(), callsign.c_str());

	socket.close();

	delete[] buffer;

	return true;
}
コード例 #10
0
ファイル: xh_notbk.cpp プロジェクト: gitrider/wxsj2
wxObject *wxNotebookXmlHandler::DoCreateResource()
{
    if (m_class == wxT("notebookpage"))
    {
        wxXmlNode *n = GetParamNode(wxT("object"));

        if ( !n )
            n = GetParamNode(wxT("object_ref"));

        if (n)
        {
            bool old_ins = m_isInside;
            m_isInside = false;
            wxObject *item = CreateResFromNode(n, m_notebook, NULL);
            m_isInside = old_ins;
            wxWindow *wnd = wxDynamicCast(item, wxWindow);

            if (wnd)
            {
                m_notebook->AddPage(wnd, GetText(wxT("label")),
                                         GetBool(wxT("selected")));
                if ( HasParam(wxT("bitmap")) )
                {
                    wxBitmap bmp = GetBitmap(wxT("bitmap"), wxART_OTHER);
                    wxImageList *imgList = m_notebook->GetImageList();
                    if ( imgList == NULL )
                    {
                        imgList = new wxImageList( bmp.GetWidth(), bmp.GetHeight() );
                        m_notebook->AssignImageList( imgList );
                    }
                    int imgIndex = imgList->Add(bmp);
                    m_notebook->SetPageImage(m_notebook->GetPageCount()-1, imgIndex );
                }
            }
            else
                wxLogError(wxT("Error in resource."));
            return wnd;
        }
        else
        {
            wxLogError(wxT("Error in resource: no control within notebook's <page> tag."));
            return NULL;
        }
    }

    else
    {
        XRC_MAKE_INSTANCE(nb, wxNotebook)

        nb->Create(m_parentAsWindow,
                   GetID(),
                   GetPosition(), GetSize(),
                   GetStyle(wxT("style")),
                   GetName());

        SetupWindow(nb);

        wxNotebook *old_par = m_notebook;
        m_notebook = nb;
        bool old_ins = m_isInside;
        m_isInside = true;
        CreateChildren(m_notebook, true/*only this handler*/);
        m_isInside = old_ins;
        m_notebook = old_par;

        return nb;
    }
}
コード例 #11
0
ファイル: nativdlg.cpp プロジェクト: 252525fb/rpcs3
wxWindow* wxWindow::CreateWindowFromHWND(wxWindow* parent, WXHWND hWnd)
{
    wxString str(wxGetWindowClass(hWnd));
    str.UpperCase();

    long id = wxGetWindowId(hWnd);
    long style = GetWindowLong((HWND) hWnd, GWL_STYLE);

    wxWindow* win = NULL;

    if (str == wxT("BUTTON"))
    {
        int style1 = (style & 0xFF);
#if wxUSE_CHECKBOX
        if ((style1 == BS_3STATE) || (style1 == BS_AUTO3STATE) || (style1 == BS_AUTOCHECKBOX) ||
            (style1 == BS_CHECKBOX))
        {
            win = new wxCheckBox;
        }
        else
#endif
#if wxUSE_RADIOBTN
        if ((style1 == BS_AUTORADIOBUTTON) || (style1 == BS_RADIOBUTTON))
        {
            win = new wxRadioButton;
        }
        else
#endif
#if wxUSE_BMPBUTTON
#if defined(__WIN32__) && defined(BS_BITMAP)
        if (style & BS_BITMAP)
        {
            // TODO: how to find the bitmap?
            win = new wxBitmapButton;
            wxLogError(wxT("Have not yet implemented bitmap button as BS_BITMAP button."));
        }
        else
#endif
        if (style1 == BS_OWNERDRAW)
        {
            // TODO: how to find the bitmap?
            // TODO: can't distinguish between bitmap button and bitmap static.
            // Change implementation of wxStaticBitmap to SS_BITMAP.
            // PROBLEM: this assumes that we're using resource-based bitmaps.
            // So maybe need 2 implementations of bitmap buttons/static controls,
            // with a switch in the drawing code. Call default proc if BS_BITMAP.
            win = new wxBitmapButton;
        }
        else
#endif
#if wxUSE_BUTTON
        if ((style1 == BS_PUSHBUTTON) || (style1 == BS_DEFPUSHBUTTON))
        {
            win = new wxButton;
        }
        else
#endif
#if wxUSE_STATBOX
        if (style1 == BS_GROUPBOX)
        {
            win = new wxStaticBox;
        }
        else
#endif
        {
            wxLogError(wxT("Don't know what kind of button this is: id = %ld"),
                       id);
        }
    }
#if wxUSE_COMBOBOX
    else if (str == wxT("COMBOBOX"))
    {
        win = new wxComboBox;
    }
#endif
#if wxUSE_TEXTCTRL
    // TODO: Problem if the user creates a multiline - but not rich text - text control,
    // since wxWin assumes RichEdit control for this. Should have m_isRichText in
    // wxTextCtrl. Also, convert as much of the window style as is necessary
    // for correct functioning.
    // Could have wxWindow::AdoptAttributesFromHWND(WXHWND)
    // to be overridden by each control class.
    else if (str == wxT("EDIT"))
    {
        win = new wxTextCtrl;
    }
#endif
#if wxUSE_LISTBOX
    else if (str == wxT("LISTBOX"))
    {
        win = new wxListBox;
    }
#endif
#if wxUSE_SCROLLBAR
    else if (str == wxT("SCROLLBAR"))
    {
        win = new wxScrollBar;
    }
#endif
#if wxUSE_SPINBTN
    else if (str == wxT("MSCTLS_UPDOWN32"))
    {
        win = new wxSpinButton;
    }
#endif
#if wxUSE_SLIDER
    else if (str == wxT("MSCTLS_TRACKBAR32"))
    {
        // Need to ascertain if it's horiz or vert
        win = new wxSlider;
    }
#endif // wxUSE_SLIDER
#if wxUSE_STATTEXT
    else if (str == wxT("STATIC"))
    {
        int style1 = (style & 0xFF);

        if ((style1 == SS_LEFT) || (style1 == SS_RIGHT)
#ifndef __WXWINCE__
            || (style1 == SS_SIMPLE)
#endif
            )
            win = new wxStaticText;
#if wxUSE_STATBMP
#if defined(__WIN32__) && defined(BS_BITMAP)
        else if (style1 == SS_BITMAP)
        {
            win = new wxStaticBitmap;

            // Help! this doesn't correspond with the wxWin implementation.
            wxLogError(wxT("Please make SS_BITMAP statics into owner-draw buttons."));
        }
#endif
#endif /* wxUSE_STATBMP */
    }
#endif
    else
    {
        wxString msg(wxT("Don't know how to convert from Windows class "));
        msg += str;
        wxLogError(msg);
    }

    if (win)
    {
        parent->AddChild(win);
        win->SetEventHandler(win);
        win->SetHWND(hWnd);
        win->SetId(id);
        win->SubclassWin(hWnd);
        win->AdoptAttributesFromHWND();
        win->SetupColours();
    }

    return win;
}
コード例 #12
0
ファイル: regex.cpp プロジェクト: BauerBox/wxWidgets
int wxRegExImpl::Replace(wxString *text,
                         const wxString& replacement,
                         size_t maxMatches) const
{
    wxCHECK_MSG( text, wxNOT_FOUND, wxT("NULL text in wxRegEx::Replace") );
    wxCHECK_MSG( IsValid(), wxNOT_FOUND, wxT("must successfully Compile() first") );

    // the input string
#ifndef WXREGEX_CONVERT_TO_MB
    const wxChar *textstr = text->c_str();
    size_t textlen = text->length();
#else
    const wxWX2MBbuf textstr = WXREGEX_CHAR(*text);
    if (!textstr)
    {
        wxLogError(_("Failed to find match for regular expression: %s"),
                   GetErrorMsg(0, true).c_str());
        return 0;
    }
    size_t textlen = strlen(textstr);
    text->clear();
#endif

    // the replacement text
    wxString textNew;

    // the result, allow 25% extra
    wxString result;
    result.reserve(5 * textlen / 4);

    // attempt at optimization: don't iterate over the string if it doesn't
    // contain back references at all
    bool mayHaveBackrefs =
        replacement.find_first_of(wxT("\\&")) != wxString::npos;

    if ( !mayHaveBackrefs )
    {
        textNew = replacement;
    }

    // the position where we start looking for the match
    size_t matchStart = 0;

    // number of replacement made: we won't make more than maxMatches of them
    // (unless maxMatches is 0 which doesn't limit the number of replacements)
    size_t countRepl = 0;

    // note that "^" shouldn't match after the first call to Matches() so we
    // use wxRE_NOTBOL to prevent it from happening
    while ( (!maxMatches || countRepl < maxMatches) &&
             Matches(
#ifndef WXREGEX_CONVERT_TO_MB
                    textstr + matchStart,
#else
                    textstr.data() + matchStart,
#endif
                    countRepl ? wxRE_NOTBOL : 0
                    WXREGEX_IF_NEED_LEN(textlen - matchStart)) )
    {
        // the string possibly contains back references: we need to calculate
        // the replacement text anew after each match
        if ( mayHaveBackrefs )
        {
            mayHaveBackrefs = false;
            textNew.clear();
            textNew.reserve(replacement.length());

            for ( const wxChar *p = replacement.c_str(); *p; p++ )
            {
                size_t index = (size_t)-1;

                if ( *p == wxT('\\') )
                {
                    if ( wxIsdigit(*++p) )
                    {
                        // back reference
                        wxChar *end;
                        index = (size_t)wxStrtoul(p, &end, 10);
                        p = end - 1; // -1 to compensate for p++ in the loop
                    }
                    //else: backslash used as escape character
                }
                else if ( *p == wxT('&') )
                {
                    // treat this as "\0" for compatbility with ed and such
                    index = 0;
                }

                // do we have a back reference?
                if ( index != (size_t)-1 )
                {
                    // yes, get its text
                    size_t start, len;
                    if ( !GetMatch(&start, &len, index) )
                    {
                        wxFAIL_MSG( wxT("invalid back reference") );

                        // just eat it...
                    }
                    else
                    {
                        textNew += wxString(
#ifndef WXREGEX_CONVERT_TO_MB
                                textstr
#else
                                textstr.data()
#endif
                                + matchStart + start,
                                *wxConvCurrent, len);

                        mayHaveBackrefs = true;
                    }
                }
                else // ordinary character
                {
                    textNew += *p;
                }
            }
        }

        size_t start, len;
        if ( !GetMatch(&start, &len) )
        {
            // we did have match as Matches() returned true above!
            wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") );

            return wxNOT_FOUND;
        }

        // an insurance against implementations that don't grow exponentially
        // to ensure building the result takes linear time
        if (result.capacity() < result.length() + start + textNew.length())
            result.reserve(2 * result.length());

#ifndef WXREGEX_CONVERT_TO_MB
        result.append(*text, matchStart, start);
#else
        result.append(wxString(textstr.data() + matchStart, *wxConvCurrent, start));
#endif
        matchStart += start;
        result.append(textNew);

        countRepl++;

        matchStart += len;
    }

#ifndef WXREGEX_CONVERT_TO_MB
    result.append(*text, matchStart, wxString::npos);
#else
    result.append(wxString(textstr.data() + matchStart, *wxConvCurrent));
#endif
    *text = result;

    return countRepl;
}
コード例 #13
0
ファイル: regex.cpp プロジェクト: BauerBox/wxWidgets
bool wxRegExImpl::Compile(const wxString& expr, int flags)
{
    Reinit();

#ifdef WX_NO_REGEX_ADVANCED
#   define FLAVORS wxRE_BASIC
#else
#   define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
    wxASSERT_MSG( (flags & FLAVORS) != FLAVORS,
                  wxT("incompatible flags in wxRegEx::Compile") );
#endif
    wxASSERT_MSG( !(flags & ~(FLAVORS | wxRE_ICASE | wxRE_NOSUB | wxRE_NEWLINE)),
                  wxT("unrecognized flags in wxRegEx::Compile") );

    // translate our flags to regcomp() ones
    int flagsRE = 0;
    if ( !(flags & wxRE_BASIC) )
    {
#ifndef WX_NO_REGEX_ADVANCED
        if (flags & wxRE_ADVANCED)
            flagsRE |= REG_ADVANCED;
        else
#endif
            flagsRE |= REG_EXTENDED;
    }
    if ( flags & wxRE_ICASE )
        flagsRE |= REG_ICASE;
    if ( flags & wxRE_NOSUB )
        flagsRE |= REG_NOSUB;
    if ( flags & wxRE_NEWLINE )
        flagsRE |= REG_NEWLINE;

    // compile it
#ifdef WXREGEX_USING_BUILTIN
    bool conv = true;
    // FIXME-UTF8: use wc_str() after removing ANSI build
    int errorcode = wx_re_comp(&m_RegEx, expr.c_str(), expr.length(), flagsRE);
#else
    // FIXME-UTF8: this is potentially broken, we shouldn't even try it
    //             and should always use builtin regex library (or PCRE?)
    const wxWX2MBbuf conv = expr.mbc_str();
    int errorcode = conv ? regcomp(&m_RegEx, conv, flagsRE) : REG_BADPAT;
#endif

    if ( errorcode )
    {
        wxLogError(_("Invalid regular expression '%s': %s"),
                   expr.c_str(), GetErrorMsg(errorcode, !conv).c_str());

        m_isCompiled = false;
    }
    else // ok
    {
        // don't allocate the matches array now, but do it later if necessary
        if ( flags & wxRE_NOSUB )
        {
            // we don't need it at all
            m_nMatches = 0;
        }
        else
        {
            // we will alloc the array later (only if really needed) but count
            // the number of sub-expressions in the regex right now

            // there is always one for the whole expression
            m_nMatches = 1;

            // and some more for bracketed subexperessions
            for ( const wxChar *cptr = expr.c_str(); *cptr; cptr++ )
            {
                if ( *cptr == wxT('\\') )
                {
                    // in basic RE syntax groups are inside \(...\)
                    if ( *++cptr == wxT('(') && (flags & wxRE_BASIC) )
                    {
                        m_nMatches++;
                    }
                }
                else if ( *cptr == wxT('(') && !(flags & wxRE_BASIC) )
                {
                    // we know that the previous character is not an unquoted
                    // backslash because it would have been eaten above, so we
                    // have a bare '(' and this indicates a group start for the
                    // extended syntax. '(?' is used for extensions by perl-
                    // like REs (e.g. advanced), and is not valid for POSIX
                    // extended, so ignore them always.
                    if ( cptr[1] != wxT('?') )
                        m_nMatches++;
                }
            }
        }

        m_isCompiled = true;
    }

    return IsValid();
}
コード例 #14
0
ファイル: listtest.cpp プロジェクト: HanruZhou/wxWidgets
void MyListCtrl::OnListKeyDown(wxListEvent& event)
{
    long item;

    if ( !wxGetKeyState(WXK_SHIFT) )
    {
        LogEvent(event, wxT("OnListKeyDown"));
        event.Skip();
        return;
    }

    switch ( event.GetKeyCode() )
    {
        case 'C': // colorize
            {
                wxListItem info;
                info.m_itemId = event.GetIndex();
                if ( info.m_itemId == -1 )
                {
                    // no item
                    break;
                }

                GetItem(info);

                wxListItemAttr *attr = info.GetAttributes();
                if ( !attr || !attr->HasTextColour() )
                {
                    info.SetTextColour(*wxCYAN);

                    SetItem(info);

                    RefreshItem(info.m_itemId);
                }
            }
            break;

        case 'N': // next
            item = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_FOCUSED);
            if ( item++ == GetItemCount() - 1 )
            {
                item = 0;
            }

            wxLogMessage(wxT("Focusing item %ld"), item);

            SetItemState(item, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
            EnsureVisible(item);
            break;

        case 'R': // show bounding rectangle
            {
                item = event.GetIndex();
                wxRect r;
                if ( !GetItemRect(item, r) )
                {
                    wxLogError(wxT("Failed to retrieve rect of item %ld"), item);
                    break;
                }

                wxLogMessage(wxT("Bounding rect of item %ld is (%d, %d)-(%d, %d)"),
                             item, r.x, r.y, r.x + r.width, r.y + r.height);
            }
            break;

        case '1': // show sub item bounding rectangle for the given column
        case '2': // (and icon/label rectangle if Shift/Ctrl is pressed)
        case '3':
        case '4': // this column is invalid but we want to test it too
            if ( InReportView() )
            {
                int subItem = event.GetKeyCode() - '1';
                item = event.GetIndex();
                wxRect r;

                int code = wxLIST_RECT_BOUNDS;
                if ( wxGetKeyState(WXK_SHIFT) )
                    code = wxLIST_RECT_ICON;
                else if ( wxGetKeyState(WXK_CONTROL) )
                    code = wxLIST_RECT_LABEL;

                if ( !GetSubItemRect(item, subItem, r, code) )
                {
                    wxLogError(wxT("Failed to retrieve rect of item %ld column %d"), item, subItem + 1);
                    break;
                }

                wxLogMessage(wxT("Bounding rect of item %ld column %d is (%d, %d)-(%d, %d)"),
                             item, subItem + 1,
                             r.x, r.y, r.x + r.width, r.y + r.height);
            }
            break;

        case 'U': // update
            if ( !IsVirtual() )
                break;

            if ( m_updated != -1 )
                RefreshItem(m_updated);

            m_updated = event.GetIndex();
            if ( m_updated != -1 )
            {
                // we won't see changes to this item as it's selected, update
                // the next one (or the first one if we're on the last item)
                if ( ++m_updated == GetItemCount() )
                    m_updated = 0;

                wxLogMessage("Updating colour of the item %ld", m_updated);
                RefreshItem(m_updated);
            }
            break;

        case 'D': // delete
            item = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
            while ( item != -1 )
            {
                DeleteItem(item);

                wxLogMessage(wxT("Item %ld deleted"), item);

                // -1 because the indices were shifted by DeleteItem()
                item = GetNextItem(item - 1,
                                   wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
            }
            break;

        case 'I': // insert
            if ( GetWindowStyle() & wxLC_REPORT )
            {
                if ( GetWindowStyle() & wxLC_VIRTUAL )
                {
                    SetItemCount(GetItemCount() + 1);
                }
                else // !virtual
                {
                    InsertItemInReportView(event.GetIndex());
                }
            }
            //else: fall through

        default:
            LogEvent(event, wxT("OnListKeyDown"));

            event.Skip();
    }
}
コード例 #15
0
ファイル: makefont.cpp プロジェクト: WinterMute/codeblocks_sf
/// Check TrueType font file whether font license allows embedding
void
MakeFont::CheckTTF(const wxString& fileName, bool& embeddingAllowed, bool& subsettingAllowed, int& cffOffset, int& cffLength)
{
  embeddingAllowed = false;
  subsettingAllowed = false;
  cffOffset = -1;
  cffLength = 0;
  if (fileName.Length() == 0)
  {
    return;
  }
  wxFileInputStream ttfFile(fileName);
  if (!ttfFile.Ok())
  {
    // Can't open file
    wxLogMessage(wxT("Error: Unable to read font file '") + fileName + wxT("'."));
    return;
  }
  // Extract number of tables
  ttfFile.SeekI(0, wxFromCurrent);
  int id = ReadInt(&ttfFile);
  if (id != 0x00010000 && id != 0x4f54544f)
  {
    wxLogError(wxT("Error: File '") + fileName + wxT("' is not a valid font file."));
    return;
  }
  short nb = ReadShort(&ttfFile);
  ttfFile.SeekI(6, wxFromCurrent);
  // Seek OS/2 table
  bool found = false;
  int offset = 0;
  int i;
  for (i = 0; i < nb; i++)
  {
    char buffer[4];
    ttfFile.Read(buffer,4);
    if (strncmp(buffer,"OS/2",4) == 0)
    {
      found = true;
      ttfFile.SeekI(4, wxFromCurrent);
      offset = ReadInt(&ttfFile);
      ttfFile.SeekI(4, wxFromCurrent);
    }
    else if (strncmp(buffer,"CFF ",4) == 0)
    {
      ttfFile.SeekI(4, wxFromCurrent);
      cffOffset = ReadInt(&ttfFile);
      cffLength = ReadInt(&ttfFile);
    }
    else
    {
      ttfFile.SeekI(12, wxFromCurrent);
    }
  }
  if (!found)
  {
    return;
  }
  ttfFile.SeekI(offset, wxFromStart);
  // Extract fsType flags
  ttfFile.SeekI(8, wxFromCurrent);
  short fsType = ReadShort(&ttfFile);
  bool rl = (fsType & 0x02) != 0;
  bool pp = (fsType & 0x04) != 0;
  bool e  = (fsType & 0x08) != 0;
  bool ns = (fsType & 0x0100) != 0;
  bool eb = (fsType & 0x0200) != 0;
  embeddingAllowed = !(rl && !pp && !e) && !eb;
  subsettingAllowed = !ns;
}
コード例 #16
0
bool CDVAPNodeD::createThread()
{
	CDVAPNodeConfig config(m_confDir, m_name);

	wxString callsign, gateway;
	DSTAR_MODE mode;
	ACK_TYPE ack;
	bool restriction, rpt1Validation;
	config.getCallsign(callsign, gateway, mode, ack, restriction, rpt1Validation);

	switch (mode) {
		case MODE_RXONLY:
			m_thread = new CDVAPNodeRXThread;
			break;
		case MODE_TXONLY:
			m_thread = new CDVAPNodeTXThread;
			break;
		default:
			m_thread = new CDVAPNodeTRXThread;
			break;
	}

	m_thread->setCallsign(callsign, gateway, mode, ack, restriction, rpt1Validation);
	wxLogInfo(wxT("Callsign set to \"%s\", gateway set to \"%s\", mode: %d, ack: %d, restriction: %d, RPT1 validation: %d"), callsign.c_str(), gateway.c_str(), int(mode), int(ack), restriction, rpt1Validation);

	wxString gatewayAddress, localAddress;
	unsigned int gatewayPort, localPort;
	config.getNetwork(gatewayAddress, gatewayPort, localAddress, localPort);
	wxLogInfo(wxT("Gateway set to %s:%u, local set to %s:%u"), gatewayAddress.c_str(), gatewayPort, localAddress.c_str(), localPort);

	if (!gatewayAddress.IsEmpty()) {
		CRepeaterProtocolHandler* handler = new CRepeaterProtocolHandler(gatewayAddress, gatewayPort, localAddress, localPort);

		bool res = handler->open();
		if (!res) {
			wxLogError(wxT("Cannot open the protocol handler"));
			return false;
		}

		m_thread->setProtocolHandler(handler);
	}

	unsigned int timeout, ackTime;
	config.getTimes(timeout, ackTime);
	m_thread->setTimes(timeout, ackTime);
	wxLogInfo(wxT("Timeout set to %u secs, ack time set to %u ms"), timeout, ackTime);

	unsigned int beaconTime;
	wxString beaconText;
	bool beaconVoice;
	TEXT_LANG language;
	config.getBeacon(beaconTime, beaconText, beaconVoice, language);
	m_thread->setBeacon(beaconTime, beaconText, beaconVoice, language);
	wxLogInfo(wxT("Beacon set to %u mins, text set to \"%s\", voice set to %d, language set to %d"), beaconTime / 60U, beaconText.c_str(), int(beaconVoice), int(language));

	wxString dvapPort;
	unsigned int dvapFrequency;
	int dvapPower, dvapSquelch, dvapOffset;
	config.getDVAP(dvapPort, dvapFrequency, dvapPower, dvapSquelch, dvapOffset);
	wxLogInfo(wxT("DVAP: port: %s, frequency: %u Hz, power: %d dBm, squelch: %d dBm, offset: %d Hz"), dvapPort.c_str(), dvapFrequency, dvapPower, dvapSquelch, dvapOffset);

	if (!dvapPort.IsEmpty()) {
		CDVAPController* dvap = new CDVAPController(dvapPort, dvapFrequency, dvapPower, dvapSquelch, dvapOffset);
		bool res = dvap->open();
		if (!res) {
			wxLogError(wxT("Unable to open the DVAP"));
			return false;
		}

		m_thread->setDVAP(dvap);
	}

	bool logging;
	config.getLogging(logging);
	m_thread->setLogging(logging, m_audioDir);
	wxLogInfo(wxT("Frame logging set to %d, in %s"), int(logging), m_audioDir.c_str());

	wxFileName wlFilename(wxFileName::GetHomeDir(), WHITELIST_FILE_NAME);
	bool exists = wlFilename.FileExists();
	if (exists) {
		CCallsignList* list = new CCallsignList(wlFilename.GetFullPath());
		bool res = list->load();
		if (!res) {
			wxLogError(wxT("Unable to open white list file - %s"), wlFilename.GetFullPath().c_str());
			delete list;
		} else {
			wxLogInfo(wxT("%u callsigns loaded into the white list"), list->getCount());
			m_thread->setWhiteList(list);
		}
	}

	wxFileName blFilename(wxFileName::GetHomeDir(), BLACKLIST_FILE_NAME);
	exists = blFilename.FileExists();
	if (exists) {
		CCallsignList* list = new CCallsignList(blFilename.GetFullPath());
		bool res = list->load();
		if (!res) {
			wxLogError(wxT("Unable to open black list file - %s"), blFilename.GetFullPath().c_str());
			delete list;
		} else {
			wxLogInfo(wxT("%u callsigns loaded into the black list"), list->getCount());
			m_thread->setBlackList(list);
		}
	}

	return true;
}
コード例 #17
0
ファイル: sj_see.cpp プロジェクト: conradstorz/silverjuke
static void SeeLogErrorObj(SEE_interpreter* interpr_, SEE_value* errorValue)
{
	// is the value an object?
	if( errorValue==NULL || SEE_VALUE_GET_TYPE(errorValue) != SEE_OBJECT )
		return;

	// is the object an array?
	SEE_object* errorObj = errorValue->u.object;
	if( errorObj == NULL )
		return;

	// get what to get ...
	wxString errorName, errorMsg, tempStr;
	long lineno = -1;

	// ... get the error name
	SEE_value tempVal;
	SEE_OBJECT_GET(interpr_, errorObj, str_name, &tempVal);
	if( SEE_VALUE_GET_TYPE(&tempVal) == SEE_STRING )
		errorName = SeeValueToWxString(interpr_, &tempVal);
	errorName.Trim(true);
	errorName.Trim(false);
	if( errorName.IsEmpty() )
		errorName = wxT("Error");

	// ... get the error message, this is formatted as "<string>:<lineno>:msg"
	SEE_OBJECT_GET(interpr_, errorObj, str_message, &tempVal);
	if( SEE_VALUE_GET_TYPE(&tempVal) == SEE_STRING )
	{
		errorMsg = SeeValueToWxString(interpr_, &tempVal);
		if( errorMsg.Find(wxT(":")) >= 0 )
		{
			tempStr = errorMsg.BeforeFirst(wxT(':'));
			errorMsg = errorMsg.AfterFirst(wxT(':'));
		}

		if( errorMsg.Find(wxT(":")) >= 0 )
		{
			tempStr = errorMsg.BeforeFirst(wxT(':'));
			if( !tempStr.ToLong(&lineno, 10) )
				lineno = -1;
			errorMsg = errorMsg.AfterFirst(wxT(':'));
		}

		errorMsg.Trim(true);
		errorMsg.Trim(false);
	}

	if( errorMsg.IsEmpty() )
		errorMsg = wxT("Unknown error");

	// ... get the line number
	if( lineno >= 1 )
		tempStr.Printf(wxT("%i"), (int)lineno);
	else
		tempStr = wxT("?");

	// ... format the line
	wxLogError(wxT("Line %s: %s: %s [%s]"),
	           tempStr.c_str(),
	           errorName.c_str(),
	           errorMsg.c_str(),
	           HOST_DATA->m_executionScope.c_str()
	          );

	// old stuff
	#if 0
	{
		SEE_value errorObjAsStr;
		SEE_ToString(interpr_, errorValue, &errorObjAsStr);

		wxString error = ::SeeValueToWxString(interpr_, &errorObjAsStr);
		if( error.IsEmpty() )
			error = wxT("Unknown error.");

		wxLogError(wxT("%s [%s]"), error.c_str(), HOST_DATA->m_executionScope.c_str());
	}
	#endif
}
コード例 #18
0
wxGzipInputStream::wxGzipInputStream(wxInputStream& stream,
                                     wxMBConv& conv /*=wxConvFile*/)
  : wxFilterInputStream(stream)
{
    m_decomp = NULL;
    m_crc = crc32(0, Z_NULL, 0);

    // Try to read the Gzip magic numbers 0x1f, 0x8b. If not found then the
    // underlying stream isn't gzipped after all, so unread the bytes taken
    // so that the underlying stream can be read directly instead.
    wxUint8 magic[2];
    size_t n = m_parent_i_stream->Read(magic, sizeof(magic)).LastRead();

    if (n < sizeof(magic) || ((magic[1] << 8) | magic[0]) != GZ_MAGIC) {
        if (n)
            m_parent_i_stream->Ungetch(magic, n);
        // Set EOF rather than error to indicate no gzip data
        m_lasterror = wxSTREAM_EOF;
        return;
    }

    wxDataInputStream ds(*m_parent_i_stream);

    // read method, flags, timestamp, extra flags and OS-code
    int method = ds.Read8();
    int flags = ds.Read8();
#if wxUSE_DATETIME
    wxUint32 datetime = ds.Read32();
    if (datetime)   // zero means not set (not -1 as usual for time_t)
        m_datetime = wxLongLong(0, datetime) * 1000L;
#else
    ds.Read32();
#endif
    ds.Read8();
    ds.Read8();

    if (flags & GZ_HEAD_CRC)
        ds.Read16();

    if (flags & GZ_EXTRA_FIELD)
        for (int i = ds.Read16(); i > 0 && m_parent_i_stream->IsOk(); i--)
            m_parent_i_stream->GetC();

    // RFC-1952 specifies ISO-8859-1 for these fields
    if (flags & GZ_ORIG_NAME) {
#if wxUSE_UNICODE
        wxTextInputStream tis(*m_parent_i_stream, wxT(" \t"), conv);
#else
        wxTextInputStream tis(*m_parent_i_stream);
        (void)conv;
#endif
        wxChar c;
        while ((c = tis.GetChar()) != 0 && m_parent_i_stream->IsOk())
            m_name += c;
    }

    if (flags & GZ_COMMENT)
        while (m_parent_i_stream->GetC() != 0 && m_parent_i_stream->IsOk())
            ;   // empty loop

    m_lasterror = wxSTREAM_READ_ERROR;
    if (!*m_parent_i_stream) {
        wxLogDebug(wxT("Error reading Gzip header"));
        return;
    }

    if (flags & GZ_RESERVED)
        wxLogWarning(_("Unsupported flag in Gzip header"));

    switch (method) {
        case Z_DEFLATED:
            m_decomp = new wxZlibInputStream(*m_parent_i_stream, wxZLIB_NO_HEADER);
            break;

        default:
            wxLogError(_("unsupported compression method in Gzip stream"));
            return; 
    }

    if (m_decomp)
        m_lasterror = m_decomp->GetLastError();
}
コード例 #19
0
// save the mxf file format
bool wxMXFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
{
    wxLogError(wxT("MXF: Couldn't save movie -> not implemented."));
    return false;
}
コード例 #20
0
void ExportMultipleDatasetsSelect(wxWindow* pWnd, wxVector<IGxDataset*> &paDatasets)
{
    wxCHECK_RET(paDatasets.size() > 1, wxT("The input dataset array is empty"));

    wxGxContainerDialog dlg(pWnd, wxID_ANY, _("Select output"));
    dlg.SetAllFilters(false);
    dlg.ShowExportFormats(true);

    wxGxObject* pGxSrcObj = dynamic_cast<wxGxObject*>(paDatasets[0]);
    wxGISEnumDatasetType eType = paDatasets[0]->GetType();
    int eSubType = paDatasets[0]->GetSubType();
    bool bDefaultSet = false;
    int eDefaulSubType = 0;

    if (eType == enumGISFeatureDataset)
    {
        for (size_t i = enumVecUnknown + 1; i < enumVecMAX; ++i)
        {
            wxGISEnumVectorDatasetType eCurrentSubType = (wxGISEnumVectorDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISFeatureDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumVecPostGIS)
        {
            dlg.AddFilter(new wxGxFeatureDatasetFilter(enumVecPostGIS), false);
        }
    }
    else if (eType == enumGISRasterDataset)
    {
        //for (size_t i = enumRasterUnknown + 1; i < enumRasterMAX; ++i)
        //{
        //    wxGISEnumRasterDatasetType eCurrentSubType = (wxGISEnumRasterDatasetType)i;
        //    if (eCurrentSubType != eSubType && IsFileDataset(enumGISRasterDataset, eCurrentSubType))
        //    {
        //        if (bDefaultSet)
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), false);
        //        }
        //        else
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), true);
        //            bDefaultSet = true;
        //            eDefaulSubType = eCurrentSubType;
        //        }
        //    }
        //}

        //if (eSubType != enumRasterPostGIS)
        //{
        //    dlg.AddFilter(new wxGxRasterDatasetFilter(enumRasterPostGIS), false);
        //}
    }
    else if (eType == enumGISTableDataset)
    {
        for (size_t i = enumTableUnknown + 1; i < enumTableMAX; ++i)
        {
            wxGISEnumTableDatasetType eCurrentSubType = (wxGISEnumTableDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISTableDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumTablePostgres)
        {
            dlg.AddFilter(new wxGxTableDatasetFilter(enumTablePostgres), false);
        }
    }


    dlg.AddShowFilter(new wxGxFolderFilter());
    dlg.AddShowFilter(new wxGxRemoteDBSchemaFilter());
    dlg.ShowCreateButton(true);

    wxGxObject* pGxParentObj = pGxSrcObj->GetParent();
    wxString sStartLoc;

    if (pGxParentObj)
    {
        while (NULL != pGxParentObj)
        {
            wxGxObjectContainer* pGxCont = wxDynamicCast(pGxParentObj, wxGxObjectContainer);
            if (NULL != pGxCont && pGxCont->CanCreate(enumGISFeatureDataset, eDefaulSubType))
            {
                break;
            }
            else
            {
                pGxParentObj = pGxParentObj->GetParent();
            }
        }
        if (pGxParentObj)
        {
            sStartLoc = pGxParentObj->GetFullName();
        }
    }

    wxGISAppConfig oConfig = GetConfig();
    if (oConfig.IsOk())
    {
        if (eType == enumGISFeatureDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_vector_ds/path"), sStartLoc);
        }
        else if (eType == enumGISRasterDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_raster_ds/path"), sStartLoc);
        }
        else if (eType == enumGISTableDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_table_ds/path"), sStartLoc);
        }
    }

    if (!sStartLoc.IsEmpty())
        dlg.SetStartingLocation(sStartLoc);

    if (dlg.ShowModal() == wxID_OK)
    {
        wxGxObjectFilter* pFilter = dlg.GetCurrentFilter();
        if (NULL == pFilter)
        {
            wxMessageBox(_("Unexpected error"), _("Error"), wxCENTRE | wxOK | wxICON_ERROR, pWnd);
            wxLogError(_("Null wxGxObjectFilter returned"));
            return;
        }

        CPLString sPath = dlg.GetPath();
        wxString sCatalogPath = dlg.GetLocation()->GetFullName();

        if (oConfig.IsOk())
        {
            if (eType == enumGISFeatureDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_vector_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISRasterDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_raster_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISTableDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/expm_table_ds/path"), sCatalogPath);
            }
        }

        //TODO: Now we create the copies (new names) instead of overwrite, but should show table with exist names and new names. If user set the same name - overwrite
        // |----------------|------------------|
        // |    dataset1    |  dataset1 (1)    |
        // |    dataset2    |  dataset2 (1)    |
        // |    dataset3    |  dataset3 (2)    |
        // |----------------|------------------|

        wxVector<EXPORTED_DATASET> paExportDatasets;
        for (size_t i = 0; i < paDatasets.size(); ++i)
        {
            wxGxObject* pGxSrcDatasetObj = dynamic_cast<wxGxObject*>(paDatasets[i]);
            if (NULL == pGxSrcDatasetObj)
            {
                continue;
            }
            wxString sNewName = CheckUniqName(sPath, pGxSrcDatasetObj->GetBaseName(), pFilter->GetExt());
            EXPORTED_DATASET ds = { sNewName, paDatasets[i] };
            paExportDatasets.push_back(ds);
        }

        if (eType == enumGISFeatureDataset)
        {
            ExportMultipleVectorDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
        else if (eType == enumGISRasterDataset)
        {
            ExportMultipleRasterDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
        else if (eType == enumGISTableDataset)
        {
            ExportMultipleTableDatasets(pWnd, sPath, pFilter, paExportDatasets);
        }
    }
}
コード例 #21
0
ファイル: IRCDDBGatewayAppD.cpp プロジェクト: jcyfkimi/OpenDV
bool CIRCDDBGatewayAppD::createThread()
{
	CIRCDDBGatewayConfig config(m_confDir, CONFIG_FILE_NAME, m_name);

	m_thread = new CIRCDDBGatewayThread(m_logDir, m_name);

	GATEWAY_TYPE gatewayType;
	wxString gatewayCallsign, gatewayAddress, icomAddress, hbAddress, description1, description2, url;
	unsigned int icomPort, hbPort;
	double latitude, longitude;
	config.getGateway(gatewayType, gatewayCallsign, gatewayAddress, icomAddress, icomPort, hbAddress, hbPort, latitude, longitude, description1, description2, url);

	gatewayCallsign.MakeUpper();
	gatewayCallsign.Append(wxT("        "));
	gatewayCallsign.Truncate(LONG_CALLSIGN_LENGTH - 1U);

	wxString callsign = gatewayCallsign;
	callsign.Append(wxT(" "));

	gatewayCallsign.Append(wxT("G"));

	wxLogInfo(wxT("Gateway type: %d, callsign: \"%s\", address: %s, Icom address: %s:%u, homebrew address: %s:%u, latitude: %lf, longitude: %lf, description: \"%s %s\", URL: \"%s\""), int(gatewayType), gatewayCallsign.c_str(), gatewayAddress.c_str(), icomAddress.c_str(), icomPort, hbAddress.c_str(), hbPort, latitude, longitude, description1.c_str(), description2.c_str(), url.c_str());

	m_thread->setGateway(gatewayType, gatewayCallsign, gatewayAddress);

	wxString aprsHostname;
	unsigned int aprsPort;
	bool aprsEnabled;
	config.getDPRS(aprsEnabled, aprsHostname, aprsPort);
	wxLogInfo(wxT("APRS enabled: %d, host: %s:%u"), int(aprsEnabled), aprsHostname.c_str(), aprsPort);

	CAPRSWriter* aprs = NULL;
	if (aprsEnabled && !gatewayCallsign.IsEmpty() && !aprsHostname.IsEmpty() && aprsPort != 0U) {
		aprs = new CAPRSWriter(aprsHostname, aprsPort, gatewayCallsign, gatewayAddress);

		bool res = aprs->open();
		if (!res)
			wxLogError(wxT("Cannot initialise the APRS data writer"));
		else
			m_thread->setAPRSWriter(aprs);
	}

	TEXT_LANG language;
	bool infoEnabled, echoEnabled, logEnabled, dratsEnabled, dtmfEnabled;
	config.getMiscellaneous(language, infoEnabled, echoEnabled, logEnabled, dratsEnabled, dtmfEnabled);
	wxLogInfo(wxT("Language: %d, info enabled: %d, echo enabled: %d, log enabled : %d, D-RATS enabled: %d, DTMF control enabled: %d"), int(language), int(infoEnabled), int(echoEnabled), int(logEnabled), int(dratsEnabled), int(dtmfEnabled));

	CIcomRepeaterProtocolHandler* icomRepeaterHandler = NULL;
	CHBRepeaterProtocolHandler* hbRepeaterHandler = NULL;
	CDummyRepeaterProtocolHandler* dummyRepeaterHandler = NULL;

	unsigned int icomCount = 0U;

	wxString repeaterCall1, repeaterBand1, repeaterAddress1, reflector1, description11, description12, url1;
	double frequency1, offset1, range1, latitude1, longitude1, agl1;
	unsigned char band11, band12, band13;
	unsigned int repeaterPort1;
	HW_TYPE repeaterType1;
	bool atStartup1;
	RECONNECT reconnect1;
	config.getRepeater1(repeaterCall1, repeaterBand1, repeaterType1, repeaterAddress1, repeaterPort1, band11, band12, band13, reflector1, atStartup1, reconnect1, frequency1, offset1, range1, latitude1, longitude1, agl1, description11, description12, url1);

	CUtils::clean(description11, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(description12, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(url1, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));

	wxString callsign1 = callsign;
	if (!repeaterBand1.IsSameAs(wxT(" "))) {
		if (!repeaterCall1.IsEmpty()) {
			callsign1 = repeaterCall1;
			callsign1.Append(wxT("        "));
			callsign1.Truncate(LONG_CALLSIGN_LENGTH);
		}

		wxLogInfo(wxT("Repeater 1 callsign: \"%.7s%s\", hardware type: %d, address: %s:%u"), callsign1.c_str(), repeaterBand1.c_str(), int(repeaterType1), repeaterAddress1.c_str(), repeaterPort1);
		wxLogInfo(wxT("Repeater 1 reflector: %s, at startup: %d, reconnect: %d"), reflector1.c_str(), atStartup1, reconnect1);
		wxLogInfo(wxT("Repeater 1 latitude: %lf, longitude: %lf, range: %.0lf kms, height: %.0lf m, frequency: %.4lf MHz, offset: %.4lf MHz"), latitude1, longitude1, range1, agl1, frequency1, offset1);
		wxLogInfo(wxT("Repeater 1 description: \"%s %s\", URL: \"%s\""), description11.c_str(), description12.c_str(), url1.c_str());

		if (repeaterType1 == HW_ICOM && !icomAddress.IsEmpty()) {
			icomRepeaterHandler = new CIcomRepeaterProtocolHandler(icomAddress, icomPort, repeaterAddress1, repeaterPort1);
			bool res = icomRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Icom repeater protocol handler"));
				delete icomRepeaterHandler;
				icomRepeaterHandler = NULL;
			}
		} else if (repeaterType1 == HW_HOMEBREW && !hbAddress.IsEmpty()) {
			hbRepeaterHandler = new CHBRepeaterProtocolHandler(hbAddress, hbPort);
			bool res = hbRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Homebrew repeater protocol handler"));
				delete hbRepeaterHandler;
				hbRepeaterHandler = NULL;
			}
		} else if (repeaterType1 == HW_DUMMY && !hbAddress.IsEmpty()) {
			dummyRepeaterHandler = new CDummyRepeaterProtocolHandler;
			bool res = dummyRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Dummy repeater protocol handler"));
				delete dummyRepeaterHandler;
				dummyRepeaterHandler = NULL;
			}
		}

		if (latitude1 == 0.0 && longitude1 == 0.0) {
			latitude1  = latitude;
			longitude1 = longitude;
		}

		if (description11.IsEmpty())
			description11 = description1;
		if (description12.IsEmpty())
			description12 = description2;

		if (url1.IsEmpty())
			url1 = url;

		if (repeaterType1 == HW_ICOM && icomRepeaterHandler != NULL) {
			wxLogInfo(wxT("Repeater 1 bands: %u %u %u"), band11, band12, band13);
			m_thread->addRepeater(callsign1, repeaterBand1, repeaterAddress1, repeaterPort1, repeaterType1, reflector1, atStartup1, reconnect1, dratsEnabled, frequency1, offset1, range1, latitude1, longitude1, agl1, description11, description12, url1, icomRepeaterHandler, band11, band12, band13);

			if (aprs != NULL)
				aprs->setPort(callsign1, repeaterBand1, frequency1, offset1, range1, latitude1, longitude1, agl1);

			icomCount++;
		} else if (repeaterType1 == HW_HOMEBREW && hbRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign1, repeaterBand1, repeaterAddress1, repeaterPort1, repeaterType1, reflector1, atStartup1, reconnect1, dratsEnabled, frequency1, offset1, range1, latitude1, longitude1, agl1, description11, description12, url1, hbRepeaterHandler);

			if (aprs != NULL)
				aprs->setPort(callsign1, repeaterBand1, frequency1, offset1, range1, latitude1, longitude1, agl1);
		} else if (repeaterType1 == HW_DUMMY && dummyRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign1, repeaterBand1, repeaterAddress1, repeaterPort1, repeaterType1, reflector1, atStartup1, reconnect1, dratsEnabled, frequency1, offset1, range1, latitude1, longitude1, agl1, description11, description12, url1, dummyRepeaterHandler);
		}
	}

	wxString repeaterCall2, repeaterBand2, repeaterAddress2, reflector2, description21, description22, url2;
	double frequency2, offset2, range2, latitude2, longitude2, agl2;
	unsigned char band21, band22, band23;
	unsigned int repeaterPort2;
	HW_TYPE repeaterType2;
	bool atStartup2;
	RECONNECT reconnect2;
	config.getRepeater2(repeaterCall2, repeaterBand2, repeaterType2, repeaterAddress2, repeaterPort2, band21, band22, band23, reflector2, atStartup2, reconnect2, frequency2, offset2, range2, latitude2, longitude2, agl2, description21, description22, url2);

	CUtils::clean(description21, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(description22, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(url2, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));

	wxString callsign2 = callsign;
	if (!repeaterBand2.IsSameAs(wxT(" "))) {
		if (!repeaterCall2.IsEmpty()) {
			callsign2 = repeaterCall2;
			callsign2.Append(wxT("        "));
			callsign2.Truncate(LONG_CALLSIGN_LENGTH);
		}

		wxLogInfo(wxT("Repeater 2 callsign: \"%.7s%s\", hardware type: %d, address: %s:%u"), callsign2.c_str(), repeaterBand2.c_str(), int(repeaterType2), repeaterAddress2.c_str(), repeaterPort2);
		wxLogInfo(wxT("Repeater 2 reflector: %s, at startup: %d, reconnect: %d"), reflector2.c_str(), atStartup2, reconnect2);
		wxLogInfo(wxT("Repeater 2 latitude: %lf, longitude: %lf, range: %.0lf kms, height: %.0lf m, frequency: %.4lf MHz, offset: %.4lf MHz"), latitude2, longitude2, range2, agl2, frequency2, offset2);
		wxLogInfo(wxT("Repeater 2 description: \"%s %s\", URL: \"%s\""), description21.c_str(), description22.c_str(), url2.c_str());

		if (callsign1.IsSameAs(callsign2) && repeaterBand1.IsSameAs(repeaterBand2)) {
			wxLogError(wxT("Repeater 2 has the same callsign and module as repeater 1, exiting"));
			return false;
		}

		if (repeaterType2 == HW_ICOM && !icomAddress.IsEmpty() && icomRepeaterHandler == NULL) {
			icomRepeaterHandler = new CIcomRepeaterProtocolHandler(icomAddress, icomPort, repeaterAddress2, repeaterPort2);
			bool res = icomRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Icom repeater protocol handler"));
				delete icomRepeaterHandler;
				icomRepeaterHandler = NULL;
			}
		} else if (repeaterType2 == HW_HOMEBREW && !hbAddress.IsEmpty() && hbRepeaterHandler == NULL) {
			hbRepeaterHandler = new CHBRepeaterProtocolHandler(hbAddress, hbPort);
			bool res = hbRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Homebrew repeater protocol handler"));
				delete hbRepeaterHandler;
				hbRepeaterHandler = NULL;
			}
		} else if (repeaterType2 == HW_DUMMY && !hbAddress.IsEmpty() && dummyRepeaterHandler == NULL) {
			dummyRepeaterHandler = new CDummyRepeaterProtocolHandler;
			bool res = dummyRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Dummy repeater protocol handler"));
				delete dummyRepeaterHandler;
				dummyRepeaterHandler = NULL;
			}
		}

		if (latitude2 == 0.0 && longitude2 == 0.0) {
			latitude2  = latitude;
			longitude2 = longitude;
		}

		if (description21.IsEmpty())
			description21 = description1;
		if (description22.IsEmpty())
			description22 = description2;

		if (url2.IsEmpty())
			url2 = url;

		if (repeaterType2 == HW_ICOM && icomRepeaterHandler != NULL) {
			wxLogInfo(wxT("Repeater 2 bands: %u %u %u"), band21, band22, band23);
			m_thread->addRepeater(callsign2, repeaterBand2, repeaterAddress2, repeaterPort2, repeaterType2, reflector2, atStartup2, reconnect2, dratsEnabled, frequency2, offset2, range2, latitude2, longitude2, agl2, description21, description22, url2, icomRepeaterHandler, band21, band22, band23);

			if (aprs != NULL)
				aprs->setPort(callsign2, repeaterBand2, frequency2, offset2, range2, latitude2, longitude2, agl2);

			icomCount++;
		} else if (repeaterType2 == HW_HOMEBREW && hbRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign2, repeaterBand2, repeaterAddress2, repeaterPort2, repeaterType2, reflector2, atStartup2, reconnect2, dratsEnabled, frequency2, offset2, range2, latitude2, longitude2, agl2, description21, description22, url2, hbRepeaterHandler);

			if (aprs != NULL)
				aprs->setPort(callsign2, repeaterBand2, frequency2, offset2, range2, latitude2, longitude2, agl2);
		} else if (repeaterType2 == HW_DUMMY && dummyRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign2, repeaterBand2, repeaterAddress2, repeaterPort2, repeaterType2, reflector2, atStartup2, reconnect2, dratsEnabled, frequency2, offset2, range2, latitude2, longitude2, agl2, description21, description22, url2, dummyRepeaterHandler);
		}
	}

	wxString repeaterCall3, repeaterBand3, repeaterAddress3, reflector3, description31, description32, url3;
	double frequency3, offset3, range3, latitude3, longitude3, agl3;
	unsigned char band31, band32, band33;
	unsigned int repeaterPort3;
	HW_TYPE repeaterType3;
	bool atStartup3;
	RECONNECT reconnect3;
	config.getRepeater3(repeaterCall3, repeaterBand3, repeaterType3, repeaterAddress3, repeaterPort3, band31, band32, band33, reflector3, atStartup3, reconnect3, frequency3, offset3, range3, latitude3, longitude3, agl3, description31, description32, url3);

	CUtils::clean(description31, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(description32, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(url3, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));

	wxString callsign3 = callsign;
	if (!repeaterBand3.IsSameAs(wxT(" "))) {
		if (!repeaterCall3.IsEmpty()) {
			callsign3 = repeaterCall3;
			callsign3.Append(wxT("        "));
			callsign3.Truncate(LONG_CALLSIGN_LENGTH);
		}

		wxLogInfo(wxT("Repeater 3 callsign: \"%.7s%s\", hardware type: %d, address: %s:%u"), callsign3.c_str(), repeaterBand3.c_str(), int(repeaterType3), repeaterAddress3.c_str(), repeaterPort3);
		wxLogInfo(wxT("Repeater 3 reflector: %s, at startup: %d, reconnect: %d"), reflector3.c_str(), atStartup3, reconnect3);
		wxLogInfo(wxT("Repeater 3 latitude: %lf, longitude: %lf, range: %.0lf kms, height: %.0lf m, frequency: %.4lf MHz, offset: %.4lf MHz"), latitude3, longitude3, range3, agl3, frequency3, offset3);
		wxLogInfo(wxT("Repeater 3 description: \"%s %s\", URL: \"%s\""), description31.c_str(), description32.c_str(), url3.c_str());

		if (callsign1.IsSameAs(callsign3) && repeaterBand1.IsSameAs(repeaterBand3)) {
			wxLogError(wxT("Repeater 3 has the same callsign and module as repeater 1, exiting"));
			return false;
		}
		if (callsign2.IsSameAs(callsign3) && repeaterBand2.IsSameAs(repeaterBand3)) {
			wxLogError(wxT("Repeater 3 has the same callsign and module as repeater 2, exiting"));
			return false;
		}

		if (repeaterType3 == HW_ICOM && !icomAddress.IsEmpty() && icomRepeaterHandler == NULL) {
			icomRepeaterHandler = new CIcomRepeaterProtocolHandler(icomAddress, icomPort, repeaterAddress3, repeaterPort3);
			bool res = icomRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Icom repeater protocol handler"));
				delete icomRepeaterHandler;
				icomRepeaterHandler = NULL;
			}
		} else if (repeaterType3 == HW_HOMEBREW && !hbAddress.IsEmpty() && hbRepeaterHandler == NULL) {
			hbRepeaterHandler = new CHBRepeaterProtocolHandler(hbAddress, hbPort);
			bool res = hbRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Homebrew repeater protocol handler"));
				delete hbRepeaterHandler;
				hbRepeaterHandler = NULL;
			}
		} else if (repeaterType3 == HW_DUMMY && !hbAddress.IsEmpty() && dummyRepeaterHandler == NULL) {
			dummyRepeaterHandler = new CDummyRepeaterProtocolHandler;
			bool res = dummyRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Dummy repeater protocol handler"));
				delete dummyRepeaterHandler;
				dummyRepeaterHandler = NULL;
			}
		}

		if (latitude3 == 0.0 && longitude3 == 0.0) {
			latitude3  = latitude;
			longitude3 = longitude;
		}

		if (description31.IsEmpty())
			description31 = description1;
		if (description32.IsEmpty())
			description32 = description2;

		if (url3.IsEmpty())
			url3 = url;

		if (repeaterType3 == HW_ICOM && icomRepeaterHandler != NULL) {
			wxLogInfo(wxT("Repeater 3 bands: %u %u %u"), band31, band32, band33);
			m_thread->addRepeater(callsign3, repeaterBand3, repeaterAddress3, repeaterPort3, repeaterType3, reflector3, atStartup3, reconnect3, dratsEnabled, frequency3, offset3, range3, latitude3, longitude3, agl3, description31, description32, url3, icomRepeaterHandler, band31, band32, band33);

			if (aprs != NULL)
				aprs->setPort(callsign3, repeaterBand3, frequency3, offset3, range3, latitude3, longitude3, agl3);

			icomCount++;
		} else if (repeaterType3 == HW_HOMEBREW && hbRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign3, repeaterBand3, repeaterAddress3, repeaterPort3, repeaterType3, reflector3, atStartup3, reconnect3, dratsEnabled, frequency3, offset3, range3, latitude3, longitude3, agl3, description31, description32, url3, hbRepeaterHandler);

			if (aprs != NULL)
				aprs->setPort(callsign3, repeaterBand3, frequency3, offset3, range3, latitude3, longitude3, agl3);
		} else if (repeaterType3 == HW_DUMMY && dummyRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign3, repeaterBand3, repeaterAddress3, repeaterPort3, repeaterType3, reflector3, atStartup3, reconnect3, dratsEnabled, frequency3, offset3, range3, latitude3, longitude3, agl3, description31, description32, url3, dummyRepeaterHandler);
		}
	}

	wxString repeaterCall4, repeaterBand4, repeaterAddress4, reflector4, description41, description42, url4;
	double frequency4, offset4, range4, latitude4, longitude4, agl4;
	unsigned char band41, band42, band43;
	unsigned int repeaterPort4;
	HW_TYPE repeaterType4;
	bool atStartup4;
	RECONNECT reconnect4;
	config.getRepeater4(repeaterCall4, repeaterBand4, repeaterType4, repeaterAddress4, repeaterPort4, band41, band42, band43, reflector4, atStartup4, reconnect4, frequency4, offset4, range4, latitude4, longitude4, agl4, description41, description42, url4);

	CUtils::clean(description41, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(description42, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));
	CUtils::clean(url4, wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,&*()-+=@/?:;"));

	wxString callsign4 = callsign;
	if (!repeaterBand4.IsSameAs(wxT(" "))) {
		if (!repeaterCall4.IsEmpty()) {
			callsign4 = repeaterCall4;
			callsign4.Append(wxT("        "));
			callsign4.Truncate(LONG_CALLSIGN_LENGTH);
		}

		wxLogInfo(wxT("Repeater 4 callsign: \"%.7s%s\", hardware type: %d, address: %s:%u"), callsign4.c_str(), repeaterBand4.c_str(), int(repeaterType4), repeaterAddress4.c_str(), repeaterPort4);
		wxLogInfo(wxT("Repeater 4 reflector: %s, at startup: %d, reconnect: %d"), reflector4.c_str(), atStartup4, reconnect4);
		wxLogInfo(wxT("Repeater 4 latitude: %lf, longitude: %lf, range: %.0lf kms, height: %.0lf m, frequency: %.4lf MHz, offset: %.4lf MHz"), latitude4, longitude4, range4, agl4, frequency4, offset4);
		wxLogInfo(wxT("Repeater 4 description: \"%s %s\", URL: \"%s\""), description41.c_str(), description42.c_str(), url4.c_str());

		if (callsign1.IsSameAs(callsign4) && repeaterBand1.IsSameAs(repeaterBand4)) {
			wxLogError(wxT("Repeater 4 has the same callsign and module as repeater 1, exiting"));
			return false;
		}
		if (callsign2.IsSameAs(callsign4) && repeaterBand2.IsSameAs(repeaterBand4)) {
			wxLogError(wxT("Repeater 4 has the same callsign and module as repeater 2, exiting"));
			return false;
		}
		if (callsign3.IsSameAs(callsign4) && repeaterBand3.IsSameAs(repeaterBand4)) {
			wxLogError(wxT("Repeater 4 has the same callsign and module as repeater 3, exiting"));
			return false;
		}

		if (repeaterType4 == HW_ICOM && !icomAddress.IsEmpty() && icomRepeaterHandler == NULL) {
			icomRepeaterHandler = new CIcomRepeaterProtocolHandler(icomAddress, icomPort, repeaterAddress4, repeaterPort4);
			bool res = icomRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Icom repeater protocol handler"));
				delete icomRepeaterHandler;
				icomRepeaterHandler = NULL;
			}
		} else if (repeaterType4 == HW_HOMEBREW && !hbAddress.IsEmpty() && hbRepeaterHandler == NULL) {
			hbRepeaterHandler = new CHBRepeaterProtocolHandler(hbAddress, hbPort);
			bool res = hbRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Homebrew repeater protocol handler"));
				delete hbRepeaterHandler;
				hbRepeaterHandler = NULL;
			}
		} else if (repeaterType4 == HW_DUMMY && !hbAddress.IsEmpty() && dummyRepeaterHandler == NULL) {
			dummyRepeaterHandler = new CDummyRepeaterProtocolHandler;
			bool res = dummyRepeaterHandler->open();
			if (!res) {
				wxLogError(wxT("Cannot open the Dummy repeater protocol handler"));
				delete dummyRepeaterHandler;
				dummyRepeaterHandler = NULL;
			}
		}

		if (latitude4 == 0.0 && longitude4 == 0.0) {
			latitude4  = latitude;
			longitude4 = longitude;
		}

		if (description41.IsEmpty())
			description41 = description1;
		if (description42.IsEmpty())
			description42 = description2;

		if (url4.IsEmpty())
			url4 = url;

		if (repeaterType4 == HW_ICOM && icomRepeaterHandler != NULL) {
			wxLogInfo(wxT("Repeater 4 bands: %u %u %u"), band41, band42, band43);
			m_thread->addRepeater(callsign4, repeaterBand4, repeaterAddress4, repeaterPort4, repeaterType4, reflector4, atStartup4, reconnect4, dratsEnabled, frequency4, offset4, range4, latitude4, longitude4, agl4, description41, description42, url4, icomRepeaterHandler, band41, band42, band43);

			if (aprs != NULL)
				aprs->setPort(callsign4, repeaterBand4, frequency4, offset4, range4, latitude4, longitude4, agl4);

			icomCount++;
		} else if (repeaterType4 == HW_HOMEBREW && hbRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign4, repeaterBand4, repeaterAddress4, repeaterPort4, repeaterType4, reflector4, atStartup4, reconnect4, dratsEnabled, frequency4, offset4, range4, latitude4, longitude4, agl4, description41, description42, url4, hbRepeaterHandler);

			if (aprs != NULL)
				aprs->setPort(callsign4, repeaterBand4, frequency4, offset4, range4, latitude4, longitude4, agl4);
		} else if (repeaterType4 == HW_DUMMY && dummyRepeaterHandler != NULL) {
			m_thread->addRepeater(callsign4, repeaterBand4, repeaterAddress4, repeaterPort4, repeaterType4, reflector4, atStartup4, reconnect4, dratsEnabled, frequency4, offset4, range4, latitude4, longitude4, agl4, description41, description42, url4, dummyRepeaterHandler);
		}
	}

	if (icomRepeaterHandler != NULL)
		icomRepeaterHandler->setCount(icomCount);

	bool ircDDBEnabled;
	wxString ircDDBHostname, ircDDBUsername, ircDDBPassword;
	config.getIrcDDB(ircDDBEnabled, ircDDBHostname, ircDDBUsername, ircDDBPassword);
	wxLogInfo(wxT("ircDDB enabled: %d, host: %s, username: %s"), int(ircDDBEnabled), ircDDBHostname.c_str(), ircDDBUsername.c_str());

	if (ircDDBEnabled) {
#if defined(__WINDOWS__)
		CIRCDDB* ircDDB = new CIRCDDB(ircDDBHostname, 9007U, ircDDBUsername, ircDDBPassword, wxT("win_") + LOG_BASE_NAME + wxT("-") + VERSION, gatewayAddress); 
#else
		CIRCDDB* ircDDB = new CIRCDDB(ircDDBHostname, 9007U, ircDDBUsername, ircDDBPassword, wxT("linux_") + LOG_BASE_NAME + wxT("-") + VERSION, gatewayAddress); 
#endif
		bool res = ircDDB->open();
		if (!res) {
			wxLogError(wxT("Cannot initialise the ircDDB protocol handler"));
			ircDDBEnabled = false;
		} else {
			m_thread->setIRC(ircDDB);
		}
	}

	if (ircDDBEnabled) {
		wxString starNetBand1, starNetCallsign1, starNetLogoff1, starNetInfo1, starNetPermanent1, link1;		// DEXTRA_LINK || DCS_LINK
		unsigned int starNetUserTimeout1, starNetGroupTimeout1;
		STARNET_CALLSIGN_SWITCH starNetCallsignSwitch1;
		bool starNetTXMsgSwitch1;
		config.getStarNet1(starNetBand1, starNetCallsign1, starNetLogoff1, starNetInfo1, starNetPermanent1, starNetUserTimeout1, starNetGroupTimeout1, starNetCallsignSwitch1, starNetTXMsgSwitch1
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
				,link1
#endif
			);

		if (!starNetCallsign1.IsEmpty() && !starNetCallsign1.IsSameAs(wxT("        "))) {
			wxString repeater = gatewayCallsign;
			repeater.Truncate(LONG_CALLSIGN_LENGTH - 1U);
			repeater.Append(starNetBand1);

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
			m_thread->addStarNet(starNetCallsign1, starNetLogoff1, repeater, starNetInfo1, starNetPermanent1, starNetUserTimeout1, starNetGroupTimeout1, starNetCallsignSwitch1, starNetTXMsgSwitch1, link1);
			wxLogInfo(wxT("STARnet group 1 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d, reflector: %s"), starNetCallsign1.c_str(), starNetLogoff1.c_str(), repeater.c_str(), starNetInfo1.c_str(), starNetPermanent1.c_str(), starNetUserTimeout1, starNetGroupTimeout1, int(starNetCallsignSwitch1), int(starNetTXMsgSwitch1), link1.c_str());
#else
			m_thread->addStarNet(starNetCallsign1, starNetLogoff1, repeater, starNetInfo1, starNetPermanent1, starNetUserTimeout1, starNetGroupTimeout1, starNetCallsignSwitch1, starNetTXMsgSwitch1);
			wxLogInfo(wxT("STARnet group 1 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d"), starNetCallsign1.c_str(), starNetLogoff1.c_str(), repeater.c_str(), starNetInfo1.c_str(), starNetPermanent1.c_str(), starNetUserTimeout1, starNetGroupTimeout1, int(starNetCallsignSwitch1), int(starNetTXMsgSwitch1));
#endif
		}

		wxString starNetBand2, starNetCallsign2, starNetLogoff2, starNetInfo2, starNetPermanent2, link2;		// DEXTRA_LINK || DCS_LINK
		unsigned int starNetUserTimeout2, starNetGroupTimeout2;
		STARNET_CALLSIGN_SWITCH starNetCallsignSwitch2;
		bool starNetTXMsgSwitch2;
		config.getStarNet2(starNetBand2, starNetCallsign2, starNetLogoff2, starNetInfo2, starNetPermanent2, starNetUserTimeout2, starNetGroupTimeout2, starNetCallsignSwitch2, starNetTXMsgSwitch2
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
				,link2
#endif
			);

		if (!starNetCallsign2.IsEmpty() && !starNetCallsign2.IsSameAs(wxT("        "))) {
			wxString repeater = gatewayCallsign;
			repeater.Truncate(LONG_CALLSIGN_LENGTH - 1U);
			repeater.Append(starNetBand2);

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
			m_thread->addStarNet(starNetCallsign2, starNetLogoff2, repeater, starNetInfo2, starNetPermanent2, starNetUserTimeout2, starNetGroupTimeout2, starNetCallsignSwitch2, starNetTXMsgSwitch2, link2);
			wxLogInfo(wxT("STARnet group 2 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d, reflector: %s"), starNetCallsign2.c_str(), starNetLogoff2.c_str(), repeater.c_str(), starNetInfo2.c_str(), starNetPermanent2.c_str(), starNetUserTimeout2, starNetGroupTimeout2, int(starNetCallsignSwitch2), int(starNetTXMsgSwitch2), link2.c_str());
#else
			m_thread->addStarNet(starNetCallsign2, starNetLogoff2, repeater, starNetInfo2, starNetPermanent2, starNetUserTimeout2, starNetGroupTimeout2, starNetCallsignSwitch2, starNetTXMsgSwitch2);
			wxLogInfo(wxT("STARnet group 2 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d"), starNetCallsign2.c_str(), starNetLogoff2.c_str(), repeater.c_str(), starNetInfo2.c_str(), starNetPermanent2.c_str(), starNetUserTimeout2, starNetGroupTimeout2, int(starNetCallsignSwitch2), int(starNetTXMsgSwitch2));
#endif
		}

		wxString starNetBand3, starNetCallsign3, starNetLogoff3, starNetInfo3, starNetPermanent3, link3;		// DEXTRA_LINK || DCS_LINK
		unsigned int starNetUserTimeout3, starNetGroupTimeout3;
		STARNET_CALLSIGN_SWITCH starNetCallsignSwitch3;
		bool starNetTXMsgSwitch3;
		config.getStarNet3(starNetBand3, starNetCallsign3, starNetLogoff3, starNetInfo3, starNetPermanent3, starNetUserTimeout3, starNetGroupTimeout3, starNetCallsignSwitch3, starNetTXMsgSwitch3
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
				,link3
#endif
			);

		if (!starNetCallsign3.IsEmpty() && !starNetCallsign3.IsSameAs(wxT("        "))) {
			wxString repeater = gatewayCallsign;
			repeater.Truncate(LONG_CALLSIGN_LENGTH - 1U);
			repeater.Append(starNetBand3);

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
			m_thread->addStarNet(starNetCallsign3, starNetLogoff3, repeater, starNetInfo3, starNetPermanent3, starNetUserTimeout3, starNetGroupTimeout3, starNetCallsignSwitch3, starNetTXMsgSwitch3, link3);
			wxLogInfo(wxT("STARnet group 3 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d, reflector: %s"), starNetCallsign3.c_str(), starNetLogoff3.c_str(), repeater.c_str(), starNetInfo3.c_str(), starNetPermanent3.c_str(), starNetUserTimeout3, starNetGroupTimeout3, int(starNetCallsignSwitch3), int(starNetTXMsgSwitch3), link3.c_str());
#else
			m_thread->addStarNet(starNetCallsign3, starNetLogoff3, repeater, starNetInfo3, starNetPermanent3, starNetUserTimeout3, starNetGroupTimeout3, starNetCallsignSwitch3, starNetTXMsgSwitch3);
			wxLogInfo(wxT("STARnet group 3 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d"), starNetCallsign3.c_str(), starNetLogoff3.c_str(), repeater.c_str(), starNetInfo3.c_str(), starNetPermanent3.c_str(), starNetUserTimeout3, starNetGroupTimeout3, int(starNetCallsignSwitch3), int(starNetTXMsgSwitch3));
#endif
		}

		wxString starNetBand4, starNetCallsign4, starNetLogoff4, starNetInfo4, starNetPermanent4, link4;		// DEXTRA_LINK || DCS_LINK
		unsigned int starNetUserTimeout4, starNetGroupTimeout4;
		STARNET_CALLSIGN_SWITCH starNetCallsignSwitch4;
		bool starNetTXMsgSwitch4;
		config.getStarNet4(starNetBand4, starNetCallsign4, starNetLogoff4, starNetInfo4, starNetPermanent4, starNetUserTimeout4, starNetGroupTimeout4, starNetCallsignSwitch4, starNetTXMsgSwitch4
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
				,link4
#endif
			);

		if (!starNetCallsign4.IsEmpty() && !starNetCallsign4.IsSameAs(wxT("        "))) {
			wxString repeater = gatewayCallsign;
			repeater.Truncate(LONG_CALLSIGN_LENGTH - 1U);
			repeater.Append(starNetBand4);

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
			m_thread->addStarNet(starNetCallsign4, starNetLogoff4, repeater, starNetInfo4, starNetPermanent4, starNetUserTimeout4, starNetGroupTimeout4, starNetCallsignSwitch4, starNetTXMsgSwitch4, link4);
			wxLogInfo(wxT("STARnet group 4 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d, reflector: %s"), starNetCallsign4.c_str(), starNetLogoff4.c_str(), repeater.c_str(), starNetInfo4.c_str(), starNetPermanent4.c_str(), starNetUserTimeout4, starNetGroupTimeout4, int(starNetCallsignSwitch4), int(starNetTXMsgSwitch4), link4.c_str());
#else
			m_thread->addStarNet(starNetCallsign4, starNetLogoff4, repeater, starNetInfo4, starNetPermanent4, starNetUserTimeout4, starNetGroupTimeout4, starNetCallsignSwitch4, starNetTXMsgSwitch4);
			wxLogInfo(wxT("STARnet group 4 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d"), starNetCallsign4.c_str(), starNetLogoff4.c_str(), repeater.c_str(), starNetInfo4.c_str(), starNetPermanent4.c_str(), starNetUserTimeout4, starNetGroupTimeout4, int(starNetCallsignSwitch4), int(starNetTXMsgSwitch4));
#endif
		}

		wxString starNetBand5, starNetCallsign5, starNetLogoff5, starNetInfo5, starNetPermanent5, link5;		// DEXTRA_LINK || DCS_LINK
		unsigned int starNetUserTimeout5, starNetGroupTimeout5;
		STARNET_CALLSIGN_SWITCH starNetCallsignSwitch5;
		bool starNetTXMsgSwitch5;
		config.getStarNet5(starNetBand5, starNetCallsign5, starNetLogoff5, starNetInfo5, starNetPermanent5, starNetUserTimeout5, starNetGroupTimeout5, starNetCallsignSwitch5, starNetTXMsgSwitch5
#if defined(DEXTRA_LINK) || defined(DCS_LINK)
				,link5
#endif
			);

		if (!starNetCallsign5.IsEmpty() && !starNetCallsign5.IsSameAs(wxT("        "))) {
			wxString repeater = gatewayCallsign;
			repeater.Truncate(LONG_CALLSIGN_LENGTH - 1U);
			repeater.Append(starNetBand5);

#if defined(DEXTRA_LINK) || defined(DCS_LINK)
			m_thread->addStarNet(starNetCallsign5, starNetLogoff5, repeater, starNetInfo5, starNetPermanent5, starNetUserTimeout5, starNetGroupTimeout5, starNetCallsignSwitch5, starNetTXMsgSwitch5, link5);
			wxLogInfo(wxT("STARnet group 5 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d, reflector: %s"), starNetCallsign5.c_str(), starNetLogoff5.c_str(), repeater.c_str(), starNetInfo5.c_str(), starNetPermanent5.c_str(), starNetUserTimeout5, starNetGroupTimeout5, int(starNetCallsignSwitch5), int(starNetTXMsgSwitch5), link5.c_str());
#else
			m_thread->addStarNet(starNetCallsign5, starNetLogoff5, repeater, starNetInfo5, starNetPermanent5, starNetUserTimeout5, starNetGroupTimeout5, starNetCallsignSwitch5, starNetTXMsgSwitch5);
			wxLogInfo(wxT("STARnet group 5 set to %s/%s on repeater %s, info: \"%s\", permanent: %s, user: %u mins, group: %u mins, callsign switch: %d, tx msg switch: %d"), starNetCallsign5.c_str(), starNetLogoff5.c_str(), repeater.c_str(), starNetInfo5.c_str(), starNetPermanent5.c_str(), starNetUserTimeout5, starNetGroupTimeout5, int(starNetCallsignSwitch5), int(starNetTXMsgSwitch5));
#endif
		}
	}

	bool dextraEnabled;
	unsigned int dextraMaxDongles;
	config.getDExtra(dextraEnabled, dextraMaxDongles);
	wxLogInfo(wxT("DExtra enabled: %d, max. dongles: %u"), int(dextraEnabled), dextraMaxDongles);

	bool remoteEnabled;
	wxString remotePassword;
	unsigned int remotePort;
	config.getRemote(remoteEnabled, remotePassword, remotePort);
	wxLogInfo(wxT("Remote enabled: %d, port: %u"), int(remoteEnabled), remotePort);
	m_thread->setRemote(remoteEnabled, remotePassword, remotePort);

	wxString dplusLogin;
	unsigned int dplusMaxDongles;
	bool dplusEnabled;
	config.getDPlus(dplusEnabled, dplusMaxDongles, dplusLogin);
	wxLogInfo(wxT("D-Plus enabled: %d, max. dongles; %u, login: %s"), int(dplusEnabled), dplusMaxDongles, dplusLogin.c_str());

	bool dcsEnabled, ccsEnabled;
	wxString ccsHost;
	config.getDCS(dcsEnabled, ccsEnabled, ccsHost);
	wxLogInfo(wxT("DCS enabled: %d, CCS enabled: %d, server: %s"), int(dcsEnabled), int(ccsEnabled), ccsHost.c_str());

	if (repeaterBand1.Len() > 1U || repeaterBand2.Len() > 1U ||
		repeaterBand3.Len() > 1U || repeaterBand4.Len() > 1U) {
		wxLogInfo(wxT("DD mode enabled"));
		m_thread->setDDModeEnabled(true);
	}

	wxFileName wlFilename(wxFileName::GetHomeDir(), PRIMARY_WHITELIST_FILE_NAME);
	bool exists = wlFilename.FileExists();

	if (!exists) {
		wlFilename.Assign(wxFileName::GetHomeDir(), SECONDARY_WHITELIST_FILE_NAME);
		exists = wlFilename.FileExists();
	}

	if (exists) {
		CCallsignList* list = new CCallsignList(wlFilename.GetFullPath());
		bool res = list->load();
		if (!res) {
			wxLogError(wxT("Unable to open the white list file - %s"), wlFilename.GetFullPath().c_str());
			delete list;
		} else {
			wxLogInfo(wxT("%u callsigns loaded into the white list"), list->getCount());
			m_thread->setWhiteList(list);
		}
	}

	wxFileName blFilename(wxFileName::GetHomeDir(), PRIMARY_BLACKLIST_FILE_NAME);
	exists = blFilename.FileExists();

	if (!exists) {
		blFilename.Assign(wxFileName::GetHomeDir(), SECONDARY_BLACKLIST_FILE_NAME);
		exists = blFilename.FileExists();
	}

	if (exists) {
		CCallsignList* list = new CCallsignList(blFilename.GetFullPath());
		bool res = list->load();
		if (!res) {
			wxLogError(wxT("Unable to open the black list file - %s"), blFilename.GetFullPath().c_str());
			delete list;
		} else {
			wxLogInfo(wxT("%u callsigns loaded into the black list"), list->getCount());
			m_thread->setBlackList(list);
		}
	}

	wxFileName rlFilename(wxFileName::GetHomeDir(), RESTRICT_FILE_NAME);
	exists = rlFilename.FileExists();
	if (exists) {
		CCallsignList* list = new CCallsignList(rlFilename.GetFullPath());
		bool res = list->load();
		if (!res) {
			wxLogError(wxT("Unable to open the restrict list file - %s"), rlFilename.GetFullPath().c_str());
			delete list;
		} else {
			wxLogInfo(wxT("%u callsigns loaded into the restrict list"), list->getCount());
			m_thread->setRestrictList(list);
		}
	}
	m_thread->setIcomRepeaterHandler(icomRepeaterHandler);
	m_thread->setHBRepeaterHandler(hbRepeaterHandler);
	m_thread->setDummyRepeaterHandler(dummyRepeaterHandler);
	m_thread->setLanguage(language);
	m_thread->setDPlus(dplusEnabled, dplusMaxDongles, dplusLogin);
	m_thread->setDExtra(dextraEnabled, dextraMaxDongles);
	m_thread->setDCS(dcsEnabled);
	m_thread->setCCS(ccsEnabled, ccsHost);
	m_thread->setInfoEnabled(infoEnabled);
	m_thread->setEchoEnabled(echoEnabled);
	m_thread->setDTMFEnabled(dtmfEnabled);
	m_thread->setLog(logEnabled);
	m_thread->setLocation(latitude, longitude);

	return true;
}
コード例 #22
0
void ExportSingleDatasetSelect(wxWindow* pWnd, IGxDataset* const pGxDataset)
{
    wxCHECK_RET(pGxDataset, wxT("The input pointer (IGxDataset*) is NULL"));


    wxGxObject* pGxSrcObj = dynamic_cast<wxGxObject*>(pGxDataset);
    wxString sName = pGxSrcObj->GetName();
    sName = ClearExt(sName);

    wxGxObjectDialog dlg(pWnd, wxID_ANY, _("Select output"));
    dlg.SetName(sName);
    dlg.SetAllowMultiSelect(false);
    dlg.SetAllFilters(false);


    wxGISEnumDatasetType eType = pGxDataset->GetType();
    int eSubType = pGxDataset->GetSubType();
    bool bDefaultSet = false;
    int eDefaulSubType = 0;

    if (eType == enumGISFeatureDataset)
    {
        for (size_t i = enumVecUnknown + 1; i < enumVecMAX; ++i)
        {
            wxGISEnumVectorDatasetType eCurrentSubType = (wxGISEnumVectorDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISFeatureDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxFeatureDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumVecPostGIS)
        {
            dlg.AddFilter(new wxGxFeatureDatasetFilter(enumVecPostGIS), false);
        }
    }
    else if (eType == enumGISRasterDataset)
    {
        //for (size_t i = enumRasterUnknown + 1; i < enumRasterMAX; ++i)
        //{
        //    wxGISEnumRasterDatasetType eCurrentSubType = (wxGISEnumRasterDatasetType)i;
        //    if (eCurrentSubType != eSubType && IsFileDataset(enumGISRasterDataset, eCurrentSubType))
        //    {
        //        if (bDefaultSet)
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), false);
        //        }
        //        else
        //        {
        //            dlg.AddFilter(new wxGxRasterDatasetFilter(eCurrentSubType), true);
        //            bDefaultSet = true;
        //            eDefaulSubType = eCurrentSubType;
        //        }
        //    }
        //}

        //if (eSubType != enumRasterPostGIS)
        //{
        //    dlg.AddFilter(new wxGxRasterDatasetFilter(enumRasterPostGIS), false);
        //}
    }
    else if (eType == enumGISTableDataset)
    {
        for (size_t i = enumTableUnknown + 1; i < enumTableMAX; ++i)
        {
            wxGISEnumTableDatasetType eCurrentSubType = (wxGISEnumTableDatasetType)i;
            if (eCurrentSubType != eSubType && IsFileDataset(enumGISTableDataset, eCurrentSubType))
            {
                if (bDefaultSet)
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), false);
                }
                else
                {
                    dlg.AddFilter(new wxGxTableDatasetFilter(eCurrentSubType), true);
                    bDefaultSet = true;
                    eDefaulSubType = eCurrentSubType;
                }
            }
        }

        if (eSubType != enumTablePostgres)
        {
            dlg.AddFilter(new wxGxTableDatasetFilter(enumTablePostgres), false);
        }
    }

    dlg.SetButtonCaption(_("Export"));
    dlg.SetOverwritePrompt(true);

    wxGxObject* pGxParentObj = pGxSrcObj->GetParent();
    wxString sStartLoc;

    if (pGxParentObj)
    {
        while (NULL != pGxParentObj)
        {
            wxGxObjectContainer* pGxCont = wxDynamicCast(pGxParentObj, wxGxObjectContainer);
            if (NULL != pGxCont && pGxCont->CanCreate(enumGISFeatureDataset, eDefaulSubType))
            {
                break;
            }
            else
            {
                pGxParentObj = pGxParentObj->GetParent();
            }
        }
        if (pGxParentObj)
        {
            sStartLoc = pGxParentObj->GetFullName();
        }
    }

    wxGISAppConfig oConfig = GetConfig();
    if (oConfig.IsOk())
    {
        if (eType == enumGISFeatureDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_vector_ds/path"), sStartLoc);
        }
        else if (eType == enumGISRasterDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_raster_ds/path"), sStartLoc);
        }
        else if (eType == enumGISTableDataset)
        {
            sStartLoc = oConfig.Read(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_table_ds/path"), sStartLoc);
        }
    }

    if (!sStartLoc.IsEmpty())
        dlg.SetStartingLocation(sStartLoc);
    if (dlg.ShowModalSave() == wxID_OK)
    {

        wxGxObjectFilter* pFilter = dlg.GetCurrentFilter();
        if (NULL == pFilter)
        {
            wxMessageBox(_("Unexpected error"), _("Error"), wxCENTRE | wxOK | wxICON_ERROR, pWnd);
            wxLogError(_("Null wxGxObjectFilter returned"));
            return;
        }

        CPLString sPath = dlg.GetPath();
        wxString sCatalogPath = dlg.GetLocation()->GetFullName();
        wxFileName oFName(dlg.GetName());
        wxString sName = oFName.GetName();

        if (oConfig.IsOk())
        {
            if (eType == enumGISFeatureDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_vector_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISRasterDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_raster_ds/path"), sCatalogPath);
            }
            else if (eType == enumGISTableDataset)
            {
                oConfig.Write(enumGISHKCU, dlg.GetAppName() + wxT("/lastpath/exp_table_ds/path"), sCatalogPath);
            }
        }

        if (eType == enumGISFeatureDataset)
        {
            ExportSingleVectorDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
        else if (eType == enumGISRasterDataset)
        {
            ExportSingleRasterDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
        else if (eType == enumGISTableDataset)
        {
            ExportSingleTableDataset(pWnd, sPath, sName, pFilter, pGxDataset);
        }
    }
}
コード例 #23
0
ファイル: clipbrd.cpp プロジェクト: chromylei/third_party
bool wxSetClipboardData(wxDataFormat dataFormat,
                        const void *data,
                        int width, int height)
{
    HANDLE handle = 0; // return value of SetClipboardData

    switch (dataFormat)
    {
        case wxDF_BITMAP:
            {
                wxBitmap *bitmap = (wxBitmap *)data;

                HDC hdcMem = CreateCompatibleDC((HDC) NULL);
                HDC hdcSrc = CreateCompatibleDC((HDC) NULL);
                HBITMAP old = (HBITMAP)
                    ::SelectObject(hdcSrc, (HBITMAP)bitmap->GetHBITMAP());
                HBITMAP hBitmap = CreateCompatibleBitmap(hdcSrc,
                                                         bitmap->GetWidth(),
                                                         bitmap->GetHeight());
                if (!hBitmap)
                {
                    SelectObject(hdcSrc, old);
                    DeleteDC(hdcMem);
                    DeleteDC(hdcSrc);
                    return false;
                }

                HBITMAP old1 = (HBITMAP) SelectObject(hdcMem, hBitmap);
                BitBlt(hdcMem, 0, 0, bitmap->GetWidth(), bitmap->GetHeight(),
                       hdcSrc, 0, 0, SRCCOPY);

                // Select new bitmap out of memory DC
                SelectObject(hdcMem, old1);

                // Set the data
                handle = ::SetClipboardData(CF_BITMAP, hBitmap);

                // Clean up
                SelectObject(hdcSrc, old);
                DeleteDC(hdcSrc);
                DeleteDC(hdcMem);
                break;
            }

#if wxUSE_WXDIB
        case wxDF_DIB:
            {
                wxBitmap *bitmap = (wxBitmap *)data;

                if ( bitmap && bitmap->IsOk() )
                {
                    wxDIB dib(*bitmap);
                    if ( dib.IsOk() )
                    {
                        handle = ::SetClipboardData(CF_DIB, dib.Detach());
                    }
                }
                break;
            }
#endif

    // VZ: I'm told that this code works, but it doesn't seem to work for me
    //     and, anyhow, I'd be highly surprised if it did. So I leave it here
    //     but IMNSHO it is completely broken.
#if wxUSE_METAFILE && !defined(wxMETAFILE_IS_ENH) && !defined(__WXWINCE__)
        case wxDF_METAFILE:
            {
                wxMetafile *wxMF = (wxMetafile *)data;
                HANDLE data = GlobalAlloc(GHND, sizeof(METAFILEPICT) + 1);
                METAFILEPICT *mf = (METAFILEPICT *)GlobalLock(data);

                mf->mm = wxMF->GetWindowsMappingMode();
                mf->xExt = width;
                mf->yExt = height;
                mf->hMF = (HMETAFILE) wxMF->GetHMETAFILE();
                GlobalUnlock(data);
                wxMF->SetHMETAFILE((WXHANDLE) NULL);

                handle = SetClipboardData(CF_METAFILEPICT, data);
                break;
            }
#endif // wxUSE_METAFILE

#if wxUSE_ENH_METAFILE && !defined(__WXWINCE__)
        case wxDF_ENHMETAFILE:
            {
                wxEnhMetaFile *emf = (wxEnhMetaFile *)data;
                wxEnhMetaFile emfCopy = *emf;

                handle = SetClipboardData(CF_ENHMETAFILE,
                                          (void *)emfCopy.GetHENHMETAFILE());
            }
            break;
#endif // wxUSE_ENH_METAFILE

        case CF_SYLK:
        case CF_DIF:
        case CF_TIFF:
        case CF_PALETTE:
        default:
            {
                wxLogError(_("Unsupported clipboard format."));
                return false;
            }

        case wxDF_OEMTEXT:
            dataFormat = wxDF_TEXT;
            // fall through

        case wxDF_TEXT:
            {
                char *s = (char *)data;

                width = strlen(s) + 1;
                height = 1;
                DWORD l = (width * height);
                HANDLE hGlobalMemory = GlobalAlloc(GHND, l);
                if ( hGlobalMemory )
                {
                    LPSTR lpGlobalMemory = (LPSTR)GlobalLock(hGlobalMemory);

                    memcpy(lpGlobalMemory, s, l);

                    GlobalUnlock(hGlobalMemory);
                }

                handle = SetClipboardData(dataFormat, hGlobalMemory);
                break;
            }

        case wxDF_HTML:
            {
                char* html = (char *)data;

                // Create temporary buffer for HTML header...
                char *buf = new char [400 + strlen(html)];
                if(!buf) return false;

                // Create a template string for the HTML header...
                strcpy(buf,
                    "Version:0.9\r\n"
                    "StartHTML:00000000\r\n"
                    "EndHTML:00000000\r\n"
                    "StartFragment:00000000\r\n"
                    "EndFragment:00000000\r\n"
                    "<html><body>\r\n"
                    "<!--StartFragment -->\r\n");

                // Append the HTML...
                strcat(buf, html);
                strcat(buf, "\r\n");
                // Finish up the HTML format...
                strcat(buf,
                    "<!--EndFragment-->\r\n"
                    "</body>\r\n"
                    "</html>");

                // Now go back, calculate all the lengths, and write out the
                // necessary header information. Note, wsprintf() truncates the
                // string when you overwrite it so you follow up with code to replace
                // the 0 appended at the end with a '\r'...
                char *ptr = strstr(buf, "StartHTML");
                sprintf(ptr+10, "%08u", (unsigned)(strstr(buf, "<html>") - buf));
                *(ptr+10+8) = '\r';

                ptr = strstr(buf, "EndHTML");
                sprintf(ptr+8, "%08u", (unsigned)strlen(buf));
                *(ptr+8+8) = '\r';

                ptr = strstr(buf, "StartFragment");
                sprintf(ptr+14, "%08u", (unsigned)(strstr(buf, "<!--StartFrag") - buf));
                *(ptr+14+8) = '\r';

                ptr = strstr(buf, "EndFragment");
                sprintf(ptr+12, "%08u", (unsigned)(strstr(buf, "<!--EndFrag") - buf));
                *(ptr+12+8) = '\r';

                // Now you have everything in place ready to put on the
                // clipboard.

                // Allocate global memory for transfer...
                HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE |GMEM_DDESHARE, strlen(buf)+4);

                // Put your string in the global memory...
                ptr = (char *)GlobalLock(hText);
                strcpy(ptr, buf);
                GlobalUnlock(hText);

                handle = ::SetClipboardData(gs_htmlcfid, hText);

                // Free memory...
                GlobalFree(hText);

                // Clean up...
                delete [] buf;
                break;
            }
    }

    if ( handle == 0 )
    {
        wxLogSysError(_("Failed to set clipboard data."));

        return false;
    }

    return true;
}
コード例 #24
0
void ExportMultipleVectorDatasets(wxWindow* pWnd, const CPLString &sPath, wxGxObjectFilter* const pFilter, wxVector<EXPORTED_DATASET> &paDatasets)
{
    wxCHECK_RET(pWnd && pFilter && paDatasets.size() > 1, wxT("The input pointer is NULL or datasets array is empty"));

    wxGISProgressDlg ProgressDlg(_("Exporting..."), _("Begin operation..."), 100, pWnd);
    ProgressDlg.SetAddPercentToMessage(false);
    ProgressDlg.ShowProgress(true);

    for (size_t i = 0; i < paDatasets.size(); ++i)
    {
        ProgressDlg.SetTitle(wxString::Format(_("Proceed %ld of %ld..."), i + 1, paDatasets.size()));
        wxGISDataset* pDataset = paDatasets[i].pDSet->GetDataset(false, &ProgressDlg);
        wxVector<wxGISFeatureDataset*> apFeatureDatasets;
        if (pDataset->GetSubsetsCount() == 0)
        {
            wxGISFeatureDataset* pFeatureDataset = wxDynamicCast(pDataset, wxGISFeatureDataset);
            if (NULL != pFeatureDataset)
            {
                pFeatureDataset->Reference();
                apFeatureDatasets.push_back(pFeatureDataset);
            }
        }
        else
        {
            for (size_t j = 0; j < pDataset->GetSubsetsCount(); ++j)
            {
                wxGISFeatureDataset* pFeatureDataset = wxDynamicCast(pDataset->GetSubset(j), wxGISFeatureDataset);
                if (NULL != pFeatureDataset)
                {
                    pFeatureDataset->Reference();
                    apFeatureDatasets.push_back(pFeatureDataset);
                }
            }
        }

        if (apFeatureDatasets.size() == 0)
        {
            wxMessageBox(_("The dataset is empty"), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
            wxLogError(_("wxGISFeatureDataset pointer is null returned"));
            return;
        }

        for (size_t j = 0; j < apFeatureDatasets.size(); ++j)
        {
            if(!ProgressDlg.Continue())
                break;
            if (!apFeatureDatasets[j]->IsOpened())
            {
                if (!apFeatureDatasets[j]->Open(0, TRUE, false, &ProgressDlg))
                {
                    wxMessageBox(ProgressDlg.GetLastMessage(), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
                    wxLogError(ProgressDlg.GetLastMessage());
                    wsDELETE(apFeatureDatasets[j]);
                    continue;
                }
            }

            if (!ExportFormat(apFeatureDatasets[j], sPath, paDatasets[i].sName, pFilter, wxGISNullSpatialFilter, NULL, NULL, true, static_cast<ITrackCancel*>(&ProgressDlg)))
            {
                wxMessageBox(ProgressDlg.GetLastMessage(), _("Error"), wxCENTRE | wxICON_ERROR | wxOK, pWnd);
                wxLogError(ProgressDlg.GetLastMessage());
                wsDELETE(apFeatureDatasets[j]);
                continue;
            }
            wsDELETE(apFeatureDatasets[j]);
        }
    }

    if (ProgressDlg.GetWarningCount() > 0 && ProgressDlg.Continue())
    {
        ShowMessageDialog(pWnd, ProgressDlg.GetWarnings());
    }
}
コード例 #25
0
ファイル: clipbrd.cpp プロジェクト: chromylei/third_party
bool wxClipboard::AddData( wxDataObject *data )
{
    if ( IsUsingPrimarySelection() )
        return false;

    wxCHECK_MSG( data, false, wxT("data is invalid") );

#if wxUSE_OLE_CLIPBOARD
    HRESULT hr = OleSetClipboard(data->GetInterface());
    if ( FAILED(hr) )
    {
        wxLogSysError(hr, _("Failed to put data on the clipboard"));

        // don't free anything in this case

        return false;
    }

    // we have to call either OleSetClipboard(NULL) or OleFlushClipboard() when
    // using OLE clipboard when the app terminates - by default, we call
    // OleSetClipboard(NULL) which won't waste RAM, but the app can call
    // wxClipboard::Flush() to change this
    m_lastDataObject = data->GetInterface();

    // we have a problem here because we should delete wxDataObject, but we
    // can't do it because IDataObject which we just gave to the clipboard
    // would try to use it when it will need the data. IDataObject is ref
    // counted and so doesn't suffer from such problem, so we release it now
    // and tell it to delete wxDataObject when it is deleted itself.
    data->SetAutoDelete();

    return true;
#elif wxUSE_DATAOBJ
    wxCHECK_MSG( wxIsClipboardOpened(), false, wxT("clipboard not open") );

    wxDataFormat format = data->GetPreferredFormat();

    switch ( format )
    {
        case wxDF_TEXT:
        case wxDF_OEMTEXT:
        {
            wxTextDataObject* textDataObject = (wxTextDataObject*) data;
            wxString str(textDataObject->GetText());
            return wxSetClipboardData(format, str.c_str());
        }

        case wxDF_BITMAP:
        case wxDF_DIB:
        {
            wxBitmapDataObject* bitmapDataObject = (wxBitmapDataObject*) data;
            wxBitmap bitmap(bitmapDataObject->GetBitmap());
            return wxSetClipboardData(data->GetPreferredFormat(), &bitmap);
        }

#if wxUSE_METAFILE
        case wxDF_METAFILE:
        {
#if 1
            // TODO
            wxLogError(wxT("Not implemented because wxMetafileDataObject does not contain width and height values."));
            return false;
#else
            wxMetafileDataObject* metaFileDataObject =
                (wxMetafileDataObject*) data;
            wxMetafile metaFile = metaFileDataObject->GetMetafile();
            return wxSetClipboardData(wxDF_METAFILE, &metaFile,
                                      metaFileDataObject->GetWidth(),
                                      metaFileDataObject->GetHeight());
#endif
        }
#endif // wxUSE_METAFILE

        default:
        {
// This didn't compile, of course
//            return wxSetClipboardData(data);
            // TODO
            wxLogError(wxT("Not implemented."));
            return false;
        }
    }
#else // !wxUSE_DATAOBJ
    return false;
#endif // wxUSE_DATAOBJ/!wxUSE_DATAOBJ
}
コード例 #26
0
// Get user name e.g. Julian Smart
bool wxGetUserName(wxChar *WXUNUSED_IN_WINCE(buf),
                   int WXUNUSED_IN_WINCE(maxSize))
{
#if defined(__WXWINCE__)
    // TODO-CE
    return false;
#elif defined(USE_NET_API)
    CHAR szUserName[256];
    if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
        return false;

    // TODO how to get the domain name?
    CHAR *szDomain = "";

    // the code is based on the MSDN example (also see KB article Q119670)
    WCHAR wszUserName[256];          // Unicode user name
    WCHAR wszDomain[256];
    LPBYTE ComputerName;

    USER_INFO_2 *ui2;         // User structure

    // Convert ANSI user name and domain to Unicode
    MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
            wszUserName, WXSIZEOF(wszUserName) );
    MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
            wszDomain, WXSIZEOF(wszDomain) );

    // Get the computer name of a DC for the domain.
    if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
    {
        wxLogError(wxT("Can not find domain controller"));

        goto error;
    }

    // Look up the user on the DC
    NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
            (LPWSTR)&wszUserName,
            2, // level - we want USER_INFO_2
            (LPBYTE *) &ui2 );
    switch ( status )
    {
        case NERR_Success:
            // ok
            break;

        case NERR_InvalidComputer:
            wxLogError(wxT("Invalid domain controller name."));

            goto error;

        case NERR_UserNotFound:
            wxLogError(wxT("Invalid user name '%s'."), szUserName);

            goto error;

        default:
            wxLogSysError(wxT("Can't get information about user"));

            goto error;
    }

    // Convert the Unicode full name to ANSI
    WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
            buf, maxSize, NULL, NULL );

    return true;

error:
    wxLogError(wxT("Couldn't look up full user name."));

    return false;
#else  // !USE_NET_API
    // Could use NIS, MS-Mail or other site specific programs
    // Use wxWidgets configuration data
    bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0;
    if ( !ok )
    {
        ok = wxGetUserId(buf, maxSize);
    }

    if ( !ok )
    {
        wxStrncpy(buf, wxT("Unknown User"), maxSize);
    }

    return true;
#endif // Win32/16
}
コード例 #27
0
bool wxTIFFHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool verbose )
{
    TIFF *tif = TIFFwxOpen( stream, "image", "w" );

    if (!tif)
    {
        if (verbose)
            wxLogError( _("TIFF: Error saving image.") );

        return false;
    }

    TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
    TIFFSetField(tif, TIFFTAG_IMAGEWIDTH,  (uint32)image->GetWidth());
    TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (uint32)image->GetHeight());
    TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
    TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    if ( image->HasOption(wxIMAGE_OPTION_RESOLUTIONX) &&
            image->HasOption(wxIMAGE_OPTION_RESOLUTIONY) )
    {
        TIFFSetField(tif, TIFFTAG_XRESOLUTION,
                        image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONX));
        TIFFSetField(tif, TIFFTAG_YRESOLUTION,
                        image->GetOptionInt(wxIMAGE_OPTION_RESOLUTIONY));
    }

    int spp = image->GetOptionInt(wxIMAGE_OPTION_SAMPLESPERPIXEL);
    if ( !spp )
        spp = 3;

    int bpp = image->GetOptionInt(wxIMAGE_OPTION_BITSPERSAMPLE);
    if ( !bpp )
        bpp=8;

    int compression = image->GetOptionInt(wxIMAGE_OPTION_COMPRESSION);
    if ( !compression )
        compression=COMPRESSION_LZW;

    TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, spp);
    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bpp);
    TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, spp*bpp == 1 ? PHOTOMETRIC_MINISBLACK
                                                        : PHOTOMETRIC_RGB);
    TIFFSetField(tif, TIFFTAG_COMPRESSION, compression);

    // scanlinesize if determined by spp and bpp
    tsize_t linebytes = (tsize_t)image->GetWidth() * spp * bpp / 8;

    if ( (image->GetWidth() % 8 > 0) && (spp * bpp < 8) )
        linebytes+=1;

    unsigned char *buf;

    if (TIFFScanlineSize(tif) > linebytes || (spp * bpp < 24))
    {
        buf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(tif));
        if (!buf)
        {
            if (verbose)
                wxLogError( _("TIFF: Couldn't allocate memory.") );

            TIFFClose( tif );

            return false;
        }
    }
    else
    {
        buf = NULL;
    }

    TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP,TIFFDefaultStripSize(tif, (uint32) -1));

    uint8 bitmask;

    unsigned char *ptr = image->GetData();
    for ( int row = 0; row < image->GetHeight(); row++ )
    {
        if ( buf )
        {
            if ( spp * bpp > 1 )
            {
                // color image
                memcpy(buf, ptr, image->GetWidth());
            }
            else // black and white image
            {
                for ( int column = 0; column < linebytes; column++ )
                {
                    uint8 reverse = 0;
                    bitmask = 1;
                    for ( int bp = 0; bp < 8; bp++ )
                    {
                        if ( ptr[column*24 + bp*3] > 0 )
                        {
                            // check only red as this is sufficient
                            reverse = reverse | 128 >> bp;
                        }

                        bitmask <<= 1;
                    }

                    buf[column] = reverse;
                }
            }
        }

        if ( TIFFWriteScanline(tif, buf ? buf : ptr, (uint32)row, 0) < 0 )
        {
            if (verbose)
                wxLogError( _("TIFF: Error writing image.") );

            TIFFClose( tif );
            if (buf)
                _TIFFfree(buf);

            return false;
        }

        ptr += image->GetWidth()*3;
    }
コード例 #28
0
void frmDatabaseDesigner::OnClickDiagramTab(wxAuiNotebookEvent &event)
{
//This event is not working by unknown reason right now.
	wxLogError(wxT("WTF?"));
}
コード例 #29
0
wxThread::ExitCode ThreadWorker::Entry()
{
    wxIPV4address ca;
    ca.Hostname(m_host);
    ca.Service(5678);
    //wxLogDebug(wxT("ThreadWorker: Connecting....."));
    m_clientSocket->SetTimeout(60);
    bool failed = false;
    WorkerEvent::evt_type etype = WorkerEvent::CONNECTING;
    if (!m_clientSocket->Connect(ca)) {
        wxLogError(wxT("Cannot connect to %s:%d"),ca.IPAddress().c_str(), ca.Service());
        failed = true;
    } else {
        //wxLogMessage(wxT("ThreadWorker: Connected. Sending %d bytes of data"),m_outsize);
        etype = WorkerEvent::SENDING;
        WorkerEvent e(this,etype);
        wxGetApp().AddPendingEvent(e);
        int to_process = m_outsize;
        do {
            m_clientSocket->Write(m_outbuf,m_outsize);
            if (m_clientSocket->Error()) {
                wxLogError(wxT("ThreadWorker: Write error"));
                failed  = true;
            }
            to_process -= m_clientSocket->LastCount();
            //wxLogDebug(wxT("EventWorker: written %d bytes, %d bytes to do"),m_clientSocket->LastCount(),to_process);
        } while(!m_clientSocket->Error() && to_process != 0);

        if (!failed) {
            etype = WorkerEvent::RECEIVING;
            WorkerEvent e(this,etype);
            wxGetApp().AddPendingEvent(e);
            to_process = m_insize;
            do {
                m_clientSocket->Read(m_inbuf,m_insize);
                if (m_clientSocket->Error()) {
                    wxLogError(wxT("ThreadWorker: Read error"));
                    failed = true;
                    break;
                }
                to_process -= m_clientSocket->LastCount();
                //wxLogDebug(wxT("EventWorker: readed %d bytes, %d bytes to do"),m_clientSocket->LastCount(),to_process);
            } while(!m_clientSocket->Error() && to_process != 0);
        }

        char* outdat = (char*)m_outbuf+2;
        if (!failed && (memcmp(m_inbuf,outdat,m_insize) != 0))
        {
            wxLogError(wxT("Data mismatch"));
            failed = true;
        }
    }
    //wxLogDebug(wxT("ThreadWorker: Finished"));
    if (!failed) {
        etype = WorkerEvent::DISCONNECTING;
        WorkerEvent e(this,etype);
        wxGetApp().AddPendingEvent(e);
    };
    m_clientSocket->Close();
    m_clientSocket->Destroy();
    m_clientSocket = NULL;
    delete [] m_outbuf;
    delete [] m_inbuf;
    if (!failed)
        etype = WorkerEvent::DONE;
    WorkerEvent e(this,etype);
    if (failed) e.setFailed();
    wxGetApp().AddPendingEvent(e);
    return 0;
}
コード例 #30
0
ファイル: xml.cpp プロジェクト: AlexHayton/decoda
bool wxXmlDocument::Load(wxInputStream& stream, const wxString& encoding, int flags)
{
#if wxUSE_UNICODE
    (void)encoding;
#else
    m_encoding = encoding;
#endif

    const size_t BUFSIZE = 1024;
    char buf[BUFSIZE];
    wxXmlParsingContext ctx;
    bool done;
    XML_Parser parser = XML_ParserCreate(NULL);

    ctx.root = ctx.node = NULL;
    ctx.encoding = wxT("UTF-8"); // default in absence of encoding=""
    ctx.conv = NULL;
#if !wxUSE_UNICODE
    if ( encoding.CmpNoCase(wxT("UTF-8")) != 0 )
        ctx.conv = new wxCSConv(encoding);
#endif
    ctx.removeWhiteOnlyNodes = (flags & wxXMLDOC_KEEP_WHITESPACE_NODES) == 0;

    XML_SetUserData(parser, (void*)&ctx);
    XML_SetElementHandler(parser, StartElementHnd, EndElementHnd);
    XML_SetCharacterDataHandler(parser, TextHnd);
    XML_SetStartCdataSectionHandler(parser, StartCdataHnd);
    XML_SetCommentHandler(parser, CommentHnd);
    XML_SetDefaultHandler(parser, DefaultHnd);
    XML_SetUnknownEncodingHandler(parser, UnknownEncodingHnd, NULL);

    bool ok = true;
    do
    {
        size_t len = stream.Read(buf, BUFSIZE).LastRead();
        done = (len < BUFSIZE);
        if (!XML_Parse(parser, buf, len, done))
        {
            wxString error(XML_ErrorString(XML_GetErrorCode(parser)),
                           *wxConvCurrent);
            wxLogError(_("XML parsing error: '%s' at line %d"),
                       error.c_str(),
                       XML_GetCurrentLineNumber(parser));
            ok = false;
            break;
        }
    } while (!done);

    if (ok)
    {
        if (!ctx.version.empty())
            SetVersion(ctx.version);
        if (!ctx.encoding.empty())
            SetFileEncoding(ctx.encoding);
        SetRoot(ctx.root);
    }
    else
    {
        delete ctx.root;
    }

    XML_ParserFree(parser);
#if !wxUSE_UNICODE
    if ( ctx.conv )
        delete ctx.conv;
#endif

    return ok;

}