Exemple #1
0
// -------------------------------------------------------------------------------- //
guGIO_Mount::guGIO_Mount( GMount * mount, wxString &mountpath )
{
    m_Mount = mount;
    g_object_ref( mount );
//    m_PanelActive = wxNOT_FOUND;
    m_MountPath = mountpath;
    if( !m_MountPath.EndsWith( wxT( "/" ) ) )
        m_MountPath.Append( wxT( "/" ) );

    char * mount_name = g_mount_get_name( m_Mount );
    if( mount_name )
    {
        m_Name = wxString( mount_name, wxConvUTF8 );
        g_free( mount_name );
    }

    guLogMessage( wxT( "Mount Path: %s" ), m_MountPath.c_str() );
    GIcon * Icon = g_mount_get_icon( mount );
    if( Icon )
    {
        char * IconStr = g_icon_to_string( Icon );
        if( IconStr )
        {
            m_IconString = wxString( IconStr, wxConvUTF8 );
            guLogMessage( wxT( "IconStr: '%s'" ), m_IconString.c_str() );
            g_free( IconStr );
        }
        g_object_unref( Icon );
    }

    wxFileConfig * Config = new wxFileConfig( wxEmptyString, wxEmptyString, m_MountPath + wxT( ".is_audio_player" ) );
    m_Id = Config->Read( wxT( "audio_player_id" ), wxString::Format( wxT( "%08lX" ), wxGetLocalTime() ) );
}
CMusikPlayer::CMusikPlayer()
	:wxEvtHandler()
        ,m_SndEngine(wxGetApp().Prefs.nSndRate,2,0)
	
{
	m_Playing		= false;
	m_Paused		= false;
	m_Fading		= false;
	m_BeginFade		= false;
	m_StartingNext	= false;
	m_Stopping		= false;
	m_SongIndex		= 0;
	m_CrossfadeType	= 0;
	m_DSP			= NULL;
	m_Playmode = MUSIK_PLAYMODE_NORMAL;
	m_NETSTREAM_read_percent = 0;
	m_NETSTREAM_bitrate = 0;
	m_NETSTREAM_status = -1;
	m_NETSTREAM_flags = 0;
	m_b_NETSTREAM_AbortConnect = false;
	m_p_NETSTREAM_Connecting = NULL;
	//--- initialize random playback ---//
	long RandomSeed = wxGetLocalTime();
	SeedRandom( RandomSeed );
	m_arrHistory.Alloc(wxGetApp().Prefs.nMaxShuffleHistory);
	//set stop watch into pause mode.
	m_bStreamIsWorkingStopWatchIsRunning = false ;
	m_NETSTREAM_last_read_percent = 0;
	m_nLastSongTime = 0;
	m_bSuppressAutomaticSongPicking = false;
	m_bPostPlayRestartInProgress = false;
}
ToasterBoxWindow::ToasterBoxWindow(wxWindow* parent, wxTimer *_parent2)
	:  ToasterBase(parent,  wxNO_BORDER|wxSTAY_ON_TOP|wxFRAME_NO_TASKBAR)
{
  startTime = wxGetLocalTime();
  parent2 = _parent2;
  sleepTime = 10;
  step = 4;
  pauseTime = 1700;
  textColor = *wxWHITE;
  popupText = _T("Change Me!");
  //the size we want the dialog to be
  wxSize dialogSize(150, 170);
  count++;


  bottomRight = wxPoint(wxGetDisplaySize().GetWidth(),
    wxGetDisplaySize().GetHeight());

  SetSize(bottomRight.x, bottomRight.y,
    dialogSize.GetWidth(), dialogSize.GetHeight());

	ToasterBase::Connect( wxEVT_ERASE_BACKGROUND, (wxObjectEventFunction)& ToasterBoxWindow::OnEraseBackground);
	ToasterBase::Connect( wxEVT_PAINT, (wxObjectEventFunction)& ToasterBoxWindow::OnPaint);
#ifndef __WXMSW__
	PushEventHandler( new wxBackgroundBitmap( charArr2wxBitmap( notif_bg_png, sizeof(notif_bg_png) ) ) );
#endif
}
bool
wxEmail::Send(wxMailMessage& message,
              const wxString& profileName,
              const wxString& sendMail)
{
    wxASSERT_MSG( !message.m_to.IsEmpty(), _T("no recipients to send mail to") ) ;


    // The 'from' field is optionally supplied by the app; it's not needed
    // by MAPI, and on Unix, will be guessed if not supplied.
    wxString from = message.m_from;
    if ( from.empty() )
    {
        from = wxGetEmailAddress();
    }

    wxString msg;
    msg << wxT("To: ");

    const size_t rcptCount = message.m_to.GetCount();
    for (size_t rcpt = 0; rcpt < rcptCount; rcpt++)
    {
        if ( rcpt )
            msg << wxT(", ");
        msg << message.m_to[rcpt];
    }

    msg << wxT("\nFrom: ") << from << wxT("\nSubject: ") << message.m_subject;
    msg << wxT("\n\n") << message.m_body;

    wxString filename;
    filename.Printf(wxT("/tmp/msg-%ld-%ld-%ld.txt"), (long) getpid(), wxGetLocalTime(),
        (long) rand());

    {
        wxFileOutputStream stream(filename);
        if (stream.Ok())
        {
            stream.Write(msg, msg.Length());
        }
        else
        {
            return FALSE ;
        }
    }

    // TODO search for a suitable sendmail if sendMail is empty
    wxString sendmail(sendMail);

    wxString cmd;
    cmd << sendmail << wxT(" < ") << filename;

    // TODO: check return code
    wxSystem(cmd.c_str());

    wxRemoveFile(filename);

    return TRUE;
}
Exemple #5
0
    virtual bool OnInit()
    {
        if (SDL_Init(SDL_INIT_AUDIO) < 0)
        {
            wxLogError(wxT("Couldn't initialize SDL: ") + wxString(SDL_GetError(), wxConvISO8859_1));
            wxLog::FlushActive();
            return false;
        }

        srand((int)wxGetLocalTime());

        WMain* wmain = new WMain(NULL);
        SetTopWindow(wmain);
        wmain->Show();

        return true;
    }
ToasterBoxWindow::ToasterBoxWindow(wxWindow* parent, wxTimer* _parent2)
    : startTime(wxGetLocalTime())
    , parent2(_parent2)
    , sleepTime(10)
    , pauseTime(1700)
    , textColor(*wxWHITE)
    , headerTextColor(*wxBLUE)
    , popupText(_T("Change Me!"))
    , shrink(false)
{
	Create(parent, wxID_ANY);
	SetWindowStyleFlag(wxNO_BORDER | wxSTAY_ON_TOP | wxFRAME_NO_TASKBAR);
	count++;
	//the size we want the dialog to be
	wxSize dialogSize(150, 170);
	bottomRight = wxPoint(wxGetDisplaySize().GetWidth(), wxGetDisplaySize().GetHeight());
	SetSize(bottomRight.x, bottomRight.y, dialogSize.GetWidth(), dialogSize.GetHeight());
	ToasterBase::Connect(wxEVT_PAINT, (wxObjectEventFunction)&ToasterBoxWindow::OnPaint);
	SetBackgroundBitmap(charArr2wxBitmap(notif_bg_png, sizeof(notif_bg_png)));
}
void ToasterBoxWindow::Notify()
{
	wxLogDebug(_T("Been up for: %d"), (int)(wxGetLocalTime() - startTime));
	ScrollDown();
}
Exemple #8
0
/* MainWindow::createStartPage
 * Builds the HTML start page and loads it into the html viewer
 * (start page tab)
 *******************************************************************/
void MainWindow::createStartPage() {
	// Get relevant resource entries
	Archive* res_archive = theArchiveManager->programResourceArchive();
	if (!res_archive)
		return;
	ArchiveEntry* entry_html = res_archive->entryAtPath("html/startpage.htm");
	ArchiveEntry* entry_logo = res_archive->entryAtPath("logo.png");
	ArchiveEntry* entry_tips = res_archive->entryAtPath("tips.txt");

	// Can't do anything without html entry
	if (!entry_html) {
		html_startpage->SetPage("<html><head><title>SLADE</title></head><body><center><h1>Something is wrong with slade.pk3 :(</h1><center></body></html>");
		return;
	}

	// Get html as string
	string html = wxString::FromAscii((const char*)(entry_html->getData()), entry_html->getSize());

	// Generate tip of the day string
	string tip = "It seems tips.txt is missing from your slade.pk3";
	if (entry_tips) {
		Tokenizer tz;
		tz.openMem((const char*)entry_tips->getData(), entry_tips->getSize(), entry_tips->getName());
		srand(wxGetLocalTime());
		int numtips = tz.getInteger();
		if (numtips < 2) // Needs at least two choices or it's kinda pointless.
			tip = "Did you know? Something is wrong with the tips.txt file in your slade.pk3.";
		else {
			int tipindex = 0;
			// Don't show same tip twice in a row
			do { tipindex = 1 + (rand() % numtips); } while (tipindex == lasttipindex);
			lasttipindex = tipindex;
			for (int a = 0; a < tipindex; a++)
				tip = tz.getToken();
		}
	}

	// Generate recent files string
	string recent;
	for (unsigned a = 0; a < 4; a++) {
		if (a >= theArchiveManager->numRecentFiles())
			break;	// No more recent files

		// Add line break if needed
		if (a > 0) recent += "<br/>\n";

		// Add recent file link
		recent += S_FMT("<a href=\"recent://%d\">%s</a>", a, theArchiveManager->recentFile(a));
	}

	// Insert tip and recent files into html
	html.Replace("#recent#", recent);
	html.Replace("#totd#", tip);

	// Write html and images to temp folder
	if (entry_logo) entry_logo->exportFile(appPath("logo.png", DIR_TEMP));
	string html_file = appPath("startpage.htm", DIR_TEMP);
	wxFile outfile(html_file, wxFile::write);
	outfile.Write(html);
	outfile.Close();

	// Load page
	html_startpage->LoadPage(html_file);

	// Clean up
	wxRemoveFile(html_file);
	wxRemoveFile(appPath("logo.png", DIR_TEMP));
}
Exemple #9
0
// Get local time as milliseconds since 00:00:00, Jan 1st 1970
wxLongLong wxGetLocalTimeMillis()
{
    wxLongLong val = 1000l;

    // If possible, use a function which avoids conversions from
    // broken-up time structures to milliseconds

#if defined(__WXPALMOS__)
    DateTimeType thenst;
    thenst.second  = 0;
    thenst.minute  = 0;
    thenst.hour    = 0;
    thenst.day     = 1;
    thenst.month   = 1;
    thenst.year    = 1970;
    thenst.weekDay = 5;
    uint32_t now = TimGetSeconds();
    uint32_t then = TimDateTimeToSeconds (&thenst);
    return SysTimeToMilliSecs(SysTimeInSecs(now - then));
#elif defined(__WXMSW__) && (defined(__WINE__) || defined(__MWERKS__))
    // This should probably be the way all WXMSW compilers should do it
    // Go direct to the OS for time

    SYSTEMTIME thenst = { 1970, 1, 4, 1, 0, 0, 0, 0 };  // 00:00:00 Jan 1st 1970
    FILETIME thenft;
    SystemTimeToFileTime( &thenst, &thenft );
    wxLongLong then( thenft.dwHighDateTime, thenft.dwLowDateTime );   // time in 100 nanoseconds

    SYSTEMTIME nowst;
    GetLocalTime( &nowst );
    FILETIME nowft;
    SystemTimeToFileTime( &nowst, &nowft );
    wxLongLong now( nowft.dwHighDateTime, nowft.dwLowDateTime );   // time in 100 nanoseconds

    return ( now - then ) / 10000.0;  // time from 00:00:00 Jan 1st 1970 to now in milliseconds

#elif defined(HAVE_GETTIMEOFDAY)
    struct timeval tp;
    if ( wxGetTimeOfDay(&tp) != -1 )
    {
        val *= tp.tv_sec;
        return (val + (tp.tv_usec / 1000));
    }
    else
    {
        wxLogError(_("wxGetTimeOfDay failed."));
        return 0;
    }
#elif defined(HAVE_FTIME)
    struct timeb tp;

    // ftime() is void and not int in some mingw32 headers, so don't
    // test the return code (well, it shouldn't fail anyhow...)
    (void)::ftime(&tp);
    val *= tp.time;
    return (val + tp.millitm);
#else // no gettimeofday() nor ftime()
    // We use wxGetLocalTime() to get the seconds since
    // 00:00:00 Jan 1st 1970 and then whatever is available
    // to get millisecond resolution.
    //
    // NOTE that this might lead to a problem if the clocks
    // use different sources, so this approach should be
    // avoided where possible.

    val *= wxGetLocalTime();

// GRG: This will go soon as all WIN32 seem to have ftime
// JACS: unfortunately not. WinCE doesn't have it.
#if defined (__WIN32__)
    // If your platform/compiler needs to use two different functions
    // to get ms resolution, please do NOT just shut off these warnings,
    // drop me a line instead at <*****@*****.**>

    // FIXME
#ifndef __WXWINCE__
    #warning "Possible clock skew bug in wxGetLocalTimeMillis()!"
#endif

    SYSTEMTIME st;
    ::GetLocalTime(&st);
    val += st.wMilliseconds;
#else // !Win32
    // If your platform/compiler does not support ms resolution please
    // do NOT just shut off these warnings, drop me a line instead at
    // <*****@*****.**>

    #if defined(__VISUALC__) || defined (__WATCOMC__)
        #pragma message("wxStopWatch will be up to second resolution!")
    #elif defined(__BORLANDC__)
        #pragma message "wxStopWatch will be up to second resolution!"
    #else
        #warning "wxStopWatch will be up to second resolution!"
    #endif // compiler
#endif

    return val;

#endif // time functions
}
Exemple #10
0
/* MainWindow::createStartPage
 * Builds the HTML start page and loads it into the html viewer
 * (start page tab)
 *******************************************************************/
void MainWindow::createStartPage(bool newtip)
{
	// Get relevant resource entries
	Archive* res_archive = theArchiveManager->programResourceArchive();
	if (!res_archive)
		return;

	// Get entries to export
	vector<ArchiveEntry*> export_entries;
	ArchiveEntry* entry_html = res_archive->entryAtPath("html/startpage.htm");
	ArchiveEntry* entry_tips = res_archive->entryAtPath("tips.txt");
	export_entries.push_back(res_archive->entryAtPath("logo.png"));
	export_entries.push_back(res_archive->entryAtPath("html/box-title-back.png"));
	//export_entries.push_back(res_archive->entryAtPath("icons/e_archive.png"));
	//export_entries.push_back(res_archive->entryAtPath("icons/e_wad.png"));
	//export_entries.push_back(res_archive->entryAtPath("icons/e_zip.png"));
	//export_entries.push_back(res_archive->entryAtPath("icons/e_folder.png"));

	// Can't do anything without html entry
	if (!entry_html)
	{
		LOG_MESSAGE(1, "No start page resource found");
		html_startpage->SetPage("<html><head><title>SLADE</title></head><body><center><h1>Something is wrong with slade.pk3 :(</h1><center></body></html>", wxEmptyString);
		return;
	}

	// Get html as string
	string html = wxString::FromAscii((const char*)(entry_html->getData()), entry_html->getSize());

	// Generate tip of the day string
	string tip = "It seems tips.txt is missing from your slade.pk3";
	if (entry_tips)
	{
		Tokenizer tz;
		tz.openMem((const char*)entry_tips->getData(), entry_tips->getSize(), entry_tips->getName());
		srand(wxGetLocalTime());
		int numtips = tz.getInteger();
		if (numtips < 2) // Needs at least two choices or it's kinda pointless.
			tip = "Did you know? Something is wrong with the tips.txt file in your slade.pk3.";
		else
		{
			int tipindex = 0;
			if (newtip || lasttipindex == 0)
			{
				// Don't show same tip twice in a row
				do { tipindex = 1 + (rand() % numtips); } while (tipindex == lasttipindex);
			}
			else
				tipindex = lasttipindex;
			
			lasttipindex = tipindex;
			for (int a = 0; a < tipindex; a++)
				tip = tz.getToken();
		}
	}

	// Generate recent files string
	string recent;
	recent += "<table class=\"box\">";
	if (theArchiveManager->numRecentFiles() > 0)
	{
		for (unsigned a = 0; a < 12; a++)
		{
			if (a >= theArchiveManager->numRecentFiles())
				break;	// No more recent files

			recent += "<tr><td valign=\"middle\" class=\"box\">";

			// Determine icon
			string fn = theArchiveManager->recentFile(a);
			string icon = "archive";
			if (fn.EndsWith(".wad"))
				icon = "wad";
			else if (fn.EndsWith(".zip") || fn.EndsWith(".pk3") || fn.EndsWith(".pke"))
				icon = "zip";
			else if (wxDirExists(fn))
				icon = "folder";

			// Add recent file link
			recent += S_FMT("<img src=\"%s.png\"></td><td valign=\"top\" class=\"box\">", icon);
			recent += S_FMT("<a href=\"recent://%d\">%s</a></td></tr>", a, fn);
		}
	}
	else
		recent += "<tr><td valign=\"top\" class=\"box\">No recently opened files</td></tr>";
	recent += "</table>";

	// Insert tip and recent files into html
	html.Replace("#recent#", recent);
	html.Replace("#totd#", tip);

	// Write html and images to temp folder
	for (unsigned a = 0; a < export_entries.size(); a++)
		export_entries[a]->exportFile(appPath(export_entries[a]->getName(), DIR_TEMP));
	Icons::exportIconPNG(Icons::ENTRY, "archive", appPath("archive.png", DIR_TEMP));
	Icons::exportIconPNG(Icons::ENTRY, "wad", appPath("wad.png", DIR_TEMP));
	Icons::exportIconPNG(Icons::ENTRY, "zip", appPath("zip.png", DIR_TEMP));
	Icons::exportIconPNG(Icons::ENTRY, "folder", appPath("folder.png", DIR_TEMP));
	string html_file = appPath("startpage.htm", DIR_TEMP);
	wxFile outfile(html_file, wxFile::write);
	outfile.Write(html);
	outfile.Close();

#ifdef __WXGTK__
	html_file = "file://" + html_file;
#endif

	// Load page
	html_startpage->ClearHistory();
	html_startpage->LoadURL(html_file);

#ifdef __WXMSW__
	html_startpage->Reload();
#endif

	// Clean up
	//wxRemoveFile(html_file);
	//wxRemoveFile(appPath("logo.png", DIR_TEMP));
}
Exemple #11
0
wxString Config::gen_SPA(wxString ip_resolver_url, wxString gpgEngine, wxString gpgHomeFolder, bool debug)
{
    CURLcode curl_Res;
    fko_ctx_t ctx;
    fwknop_options_t opts;
    int key_len = 0;
    int res;
    int hmac_str_len = 0;
    short message_type = FKO_CLIENT_TIMEOUT_NAT_ACCESS_MSG;
    short digest_type = FKO_DIGEST_SHA256;
    short hmac_type = FKO_HMAC_SHA256;
    char key_str[129] = {0}, hmac_str[129] = {0};
    char spa_msg[256] = {0};
//    char spa_buf[4096] = {0};
//    char * spa_buf_ptr;
//    char crypt_buf[4096] = {0};
    char nat_access_str[25] = {0};
//    char * hmac_buf;
//    char * spa_digest_ptr;


    memset(&opts, 0, sizeof(fwknop_options_t));

    if (this->KEY.IsEmpty() && !this->USE_GPG_CRYPT)
        return _("Key cannot be blank!");

    wxBusyInfo wait(_("Please wait, working..."));
    if (this->SERVER_PORT.CmpNoCase(wxT("random")) == 0)
    {
        srand((int)wxGetLocalTime());
        this->SERVER_PORT.Empty();
        this->SERVER_PORT << (rand()%55535 + 10000); // do this better, this isn't a horribly good random function
    }
    if (this->ACCESS_IP.CmpNoCase(wxT("Source IP")) == 0)
        this->ACCESS_IP = wxT("0.0.0.0");
    else if (this->ACCESS_IP.CmpNoCase(wxT("Resolve IP")) == 0)
    {
        std::ostringstream oss;
        curl_Res = curl_read(std::string(ip_resolver_url.mb_str()), oss);
        if (curl_Res == CURLE_OK)
        {
            wxString result_tmp = wxString::FromUTF8(oss.str().c_str());
            wxRegEx findIP( wxT("(([0-9]{1}|[0-9]{2}|[0-1][0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]{1}|[0-9]{2}|[0-1][0-9]{2}|2[0-4][0-9]|25[0-5])"));
            if (!findIP.Matches(result_tmp))
                return _("Unable to resolve our IP!");

            this->ACCESS_IP = findIP.GetMatch(result_tmp);
        } else
            return _("Libcurl returned the error: ") + wxString::FromUTF8(curl_easy_strerror(curl_Res));

    } //end resolve ip
    if (fko_new(&ctx) != FKO_SUCCESS)
        return _("Could not get new FKO context");

    if (USE_GPG_CRYPT) {
        fko_set_spa_encryption_type(ctx, FKO_ENCRYPTION_GPG);
        fko_set_gpg_exe(ctx, gpgEngine.mb_str());
        fko_set_gpg_home_dir(ctx, gpgHomeFolder.mb_str());


        fko_set_gpg_recipient(ctx, GPG_CRYPT_ID.mb_str());
        if (GPG_SIG_ID.CmpNoCase(_("None")) != 0)
        fko_set_gpg_signer(ctx, GPG_SIG_ID.mb_str());



        fko_set_spa_encryption_mode(ctx, FKO_ENC_MODE_ASYMMETRIC);

    } else {
        if (this->KEY_BASE64)
        {
            key_len = fko_base64_decode(this->KEY.mb_str(), (unsigned char *)key_str);
        } else {
            strncpy(key_str, (const char*)this->KEY.mb_str(wxConvUTF8), 128);
            key_len = (int)strlen(key_str);
        }
    }

    if (this->HMAC_BASE64)
    {
        hmac_str_len = fko_base64_decode(this->HMAC.mb_str(), (unsigned char *)hmac_str);
    } else {
        strncpy(hmac_str, (const char*)this->HMAC.mb_str(wxConvUTF8), 128);
        hmac_str_len = (int)strlen(hmac_str);
    }



    if (MESS_TYPE.CmpNoCase(wxT("Server Command")) == 0)
    {
        message_type = FKO_COMMAND_MSG;
        if (fko_set_spa_message_type(ctx, message_type) != FKO_SUCCESS)
            return _("Could not set message type");

        snprintf(spa_msg, 256, "%s,%s", (const char*)this->ACCESS_IP.mb_str(wxConvUTF8), (const char*)this->SERVER_CMD.mb_str(wxConvUTF8));
        res = fko_set_spa_message(ctx, spa_msg);
        if (res != FKO_SUCCESS)
            return _("Could not set command message");

    } else {
        if (fko_set_spa_client_timeout(ctx, wxAtoi(this->SERVER_TIMEOUT)) != FKO_SUCCESS)
            return _("Could not set SPA timeout");

        snprintf(spa_msg, 256, "%s,%s", (const char*)this->ACCESS_IP.mb_str(wxConvUTF8), (const char*)this->PORTS.mb_str(wxConvUTF8));
        if (fko_set_spa_message(ctx, spa_msg) != FKO_SUCCESS)
            return _("Could not set SPA Message");

    }
    if (this->LEGACY) { // technically should trim hmac keys
        if (fko_set_spa_encryption_mode(ctx, FKO_ENC_MODE_CBC_LEGACY_IV) != FKO_SUCCESS)
            return _("Could not set Legacy mode.");

    }
    if (!this->HMAC.IsEmpty()){
        if (this->HMAC_TYPE.CmpNoCase(wxT("MD5"))==0)
            hmac_type = FKO_HMAC_MD5;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA1"))==0)
            hmac_type = FKO_HMAC_SHA1;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA256"))==0)
            hmac_type = FKO_HMAC_SHA256;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA384"))==0)
            hmac_type = FKO_HMAC_SHA384;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA512"))==0)
            hmac_type = FKO_HMAC_SHA512;
        if (fko_set_spa_hmac_type(ctx, hmac_type) != FKO_SUCCESS)
            return _("Could not set HMAC type.");

    }
    if (this->MESS_TYPE.CmpNoCase(wxT("Nat Access")) == 0)
    {
        sprintf(nat_access_str, "%s,%s", (const char*)this->NAT_IP.mb_str(wxConvUTF8), (const char*)this->NAT_PORT.mb_str(wxConvUTF8));
        if (fko_set_spa_nat_access(ctx, nat_access_str) != FKO_SUCCESS)
            return _("Could not set nat access string.");

    } else if (this->MESS_TYPE.CmpNoCase(wxT("Local Nat Access")) == 0) {
        message_type = FKO_CLIENT_TIMEOUT_LOCAL_NAT_ACCESS_MSG;
        if (fko_set_spa_message_type(ctx, message_type) != FKO_SUCCESS)
        return _("Chould not set message type");
        sprintf(nat_access_str, "%s,%s", (const char*)this->SERVER_IP.mb_str(wxConvUTF8), (const char*)this->NAT_PORT.mb_str(wxConvUTF8));
        if (fko_set_spa_nat_access(ctx, nat_access_str) != FKO_SUCCESS)
            return _("Could not set nat access string.");
    }
    if (this->DIGEST_TYPE.CmpNoCase(wxT("MD5"))==0)
        digest_type = FKO_DIGEST_MD5;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA1"))==0)
        digest_type = FKO_DIGEST_SHA1;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA256"))==0)
        digest_type = FKO_DIGEST_SHA256;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA384"))==0)
        digest_type = FKO_DIGEST_SHA384;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA512"))==0)
        digest_type = FKO_DIGEST_SHA512;
    if (fko_set_spa_digest_type(ctx, digest_type) != FKO_SUCCESS)
        return _("Could not set SPA digest type.");
    if (fko_spa_data_final(ctx, key_str, key_len, hmac_str, hmac_str_len) != FKO_SUCCESS)
        return _("Could not generate SPA data.");

    if (fko_get_spa_data(ctx, &opts.spa_data) != FKO_SUCCESS)
        return _("Could not retrieve SPA data.");
   // if (!USE_GPG_CRYPT) {
        this->SPA_STRING = wxString::FromUTF8(opts.spa_data);
    /*} else {  //could retain this for libfko without gpg support
        fko_get_encoded_data(ctx, &spa_buf_ptr);
        fko_get_spa_digest(ctx, &spa_digest_ptr);
        sprintf(spa_buf,"%s:%s", spa_buf_ptr, spa_digest_ptr);
        ourGPG->encryptAndSign(GPG_CRYPT_ID, GPG_SIG_ID, spa_buf, crypt_buf);
        fko_set_spa_data(ctx, crypt_buf);
        fko_set_spa_hmac(ctx, hmac_str, hmac_str_len);
        fko_get_spa_hmac(ctx, &hmac_buf);
        strcat(crypt_buf, hmac_buf);
        this->SPA_STRING = wxString::FromUTF8(crypt_buf + 2);

    }*/

    if (debug) {
        wxTextEntryDialog *debugMessage = new wxTextEntryDialog(NULL, _("Debug info"), _("Debug info"),  "Source IP: " + this->ACCESS_IP +"\n" + "SPA String: " + this->SPA_STRING, wxOK | wxTE_MULTILINE );
        debugMessage->SetSize(620, 320);
        debugMessage->ShowModal();
        debugMessage->Destroy();
    }
    return _("Success");
}
Exemple #12
0
bool wxEmail::Send(wxMailMessage& message,  int sendMethod, const wxString& profileName,
    const wxString& sendMail2, const wxString& sendMail1, const wxString& sendMail0)
{
    wxASSERT_MSG( !message.m_to.IsEmpty(), _T("no recipients to send mail to") ) ;

    wxString from = message.m_from;
    if ( from.empty() )
    {
        from = wxGetEmailAddress();
    }

    wxString msg,sendmail;

    if(sendMethod == 0) {                    //with xdg-email via local mail system (MUA)

    if(wxFileExists(sendMail0))
        sendmail << sendMail0;
    else if(wxFileExists(sendMail1))
        sendmail << sendMail1;
    else {
    wxLogMessage(_T("MAIL Error: xdg-email is not installed on this computer!") );
    return false;
    }

    msg << wxT("sh") << wxT(" ") << sendmail << wxT(" --utf8");                     //command
    msg << wxT(" --subject") <<  wxT(" '") << message.m_subject  << wxT("' ");      //subject argument
    msg << wxT("--body") << wxT(" '") << message.m_body << wxT("'");                //body argument

    for (size_t rcpt = 0; rcpt < message.m_to.GetCount(); rcpt++)                   //mail to argument
        msg << wxT(" '") << message.m_to[rcpt] << wxT("'");

    wxSystem(msg.c_str());

    return true;

    } else {                                 //directly with sendmail
        msg << wxT("To: ");
        for (size_t rcpt = 0; rcpt < message.m_to.GetCount(); rcpt++) {
            if ( rcpt ) msg << wxT(", ");
            msg << message.m_to[rcpt];
        }
        msg << wxT("\nFrom: ") << from << wxT("\nSubject: ") << message.m_subject;
        msg << wxT("\n\n") << message.m_body;

        wxString filename;
        filename.Printf(wxT("/tmp/msg-%ld-%ld-%ld.txt"), (long) getpid(), wxGetLocalTime(),
            (long) rand());

        wxFileOutputStream stream(filename);
        if (stream.Ok())
            stream.Write(msg.ToUTF8(), msg.Length());
        else
            return FALSE;

        // TODO search for a suitable sendmail if sendMail is empty
        sendmail << sendMail2;

        wxString cmd;
        cmd << sendmail << wxT(" < ") << filename;

        // TODO: check return code
        wxSystem(cmd.c_str());

        wxRemoveFile(filename);

        return TRUE;
    }
}
Exemple #13
0
std::vector<cbCodeCompletionPlugin::CCToken> ClangCodeCompletion::GetAutocompList(bool isAuto, cbEditor* ed, int& tknStart, int& tknEnd)
{
#ifdef CLANGPLUGIN_TRACE_FUNCTIONS
    fprintf(stdout,"%s isAuto=%d\n", __PRETTY_FUNCTION__,(int)isAuto);
#endif
    std::vector<cbCodeCompletionPlugin::CCToken> tokens;

    int CCOutstanding = m_CCOutstanding;
    if ((CCOutstanding > 0)&&(m_CCOutstandingPos != ed->GetControl()->GetCurrentPos()))
    {
        CCOutstanding = 0;
    }

    m_CCOutstanding = 0;
    ClTranslUnitId translUnitId = m_TranslUnitId;
    if( translUnitId != GetCurrentTranslationUnitId() )
        return tokens;
    if (translUnitId == wxNOT_FOUND)
    {
        Manager::Get()->GetLogManager()->LogWarning(wxT("ClangLib: m_TranslUnitId == wxNOT_FOUND, "
                "cannot complete in file ") + ed->GetFilename());
        return tokens;
    }

    cbStyledTextCtrl* stc = ed->GetControl();
    const int style = stc->GetStyleAt(tknEnd);
    const wxChar curChar = stc->GetCharAt(tknEnd - 1);
    if (isAuto) // filter illogical cases of auto-launch
    {
        if ((curChar == wxT(':') // scope operator
                && stc->GetCharAt(tknEnd - 2) != wxT(':') )
                || ( curChar == wxT('>') // '->'
                        && stc->GetCharAt(tknEnd - 2) != wxT('-') )
                || ( wxString(wxT("<\"/")).Find(curChar) != wxNOT_FOUND // #include directive (TODO: enumerate completable include files)
                        && !stc->IsPreprocessor(style)))
        {
            return tokens;
        }
    }

    const int line = stc->LineFromPosition(tknStart);
/*
    std::map<wxString, wxString> unsavedFiles;
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* editor = edMgr->GetBuiltinEditor(i);
        if (editor && editor->GetModified())
            unsavedFiles.insert(std::make_pair(editor->GetFilename(), editor->GetControl()->GetText()));
    }
*/
    const int lnStart = stc->PositionFromLine(line);
    int column = tknStart - lnStart;
    for (; column > 0; --column)
    {
        if (!wxIsspace(stc->GetCharAt(lnStart + column - 1))
                || (column != 1 && !wxIsspace(stc->GetCharAt(lnStart + column - 2))))
        {
            break;
        }
    }

    const wxString& prefix = stc->GetTextRange(tknStart, tknEnd).Lower();
    bool includeCtors = true; // sometimes we get a lot of these
    for (int i = tknStart - 1; i > 0; --i)
    {
        wxChar chr = stc->GetCharAt(i);
        if (!wxIsspace(chr))
        {
            if (chr == wxT(';') || chr == wxT('}')) // last non-whitespace character
                includeCtors = false; // filter out ctors (they are unlikely to be wanted in this situation)
            break;
        }
    }

    std::vector<ClToken> tknResults;
    if ((CCOutstanding == 0)||(m_CCOutstandingResults.size()==0))
    {
        ClTokenPosition loc(line+1, column+1);
        //ClangProxy::CodeCompleteAtJob job( cbEVT_CLANG_SYNCTASK_FINISHED, idClangCodeCompleteTask, isAuto, ed->GetFilename(), loc, m_TranslUnitId, unsavedFiles);
        //m_Proxy.AppendPendingJob(job);
        unsigned long timeout = 40;
        if( !isAuto )
        {
            timeout = 500;
        }
        if( wxCOND_TIMEOUT == m_pClangPlugin->GetCodeCompletionAt(translUnitId, ed->GetFilename(), loc, timeout, tknResults))
        {
            if (wxGetLocalTime() - m_CCOutstandingLastMessageTime > 10)
            {
                //InfoWindow::Display(_("Code completion"), _("Busy parsing the document"), 1000);
                m_CCOutstandingLastMessageTime = wxGetLocalTime();
            }
            //std::cout<<"Timeout waiting for code completion"<<std::endl;
            m_CCOutstanding++;
            m_CCOutstandingPos = ed->GetControl()->GetCurrentPos();
            m_CCOutstandingResults.clear();
            return tokens;
        }
    }
    else
    {
        tknResults = m_CCOutstandingResults;
    }

    //m_Proxy.CodeCompleteAt(isAuto, ed->GetFilename(), line + 1, column + 1,
    //        m_TranslUnitId, unsavedFiles, tknResults);
    if (prefix.Length() > 3) // larger context, match the prefix at any point in the token
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
                tknIt != tknResults.end(); ++tknIt)
        {
            if (tknIt->name.Lower().Find(prefix) != wxNOT_FOUND && (includeCtors || tknIt->category != tcCtorPublic))
                tokens.push_back(cbCodeCompletionPlugin::CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }
    else if (prefix.IsEmpty())
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
                tknIt != tknResults.end(); ++tknIt)
        {
            // it is rather unlikely for an operator to be the desired completion
            if (!tknIt->name.StartsWith(wxT("operator")) && (includeCtors || tknIt->category != tcCtorPublic))
                tokens.push_back(cbCodeCompletionPlugin::CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }
    else // smaller context, only allow matches of the prefix at the beginning of the token
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
                tknIt != tknResults.end(); ++tknIt)
        {
            if (tknIt->name.Lower().StartsWith(prefix) && (includeCtors || tknIt->category != tcCtorPublic))
                tokens.push_back(cbCodeCompletionPlugin::CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }

    if (!tokens.empty())
    {
        if (prefix.IsEmpty() && tokens.size() > 1500) // reduce to give only top matches
        {
            std::partial_sort(tokens.begin(), tokens.begin() + 1000, tokens.end(), PrioritySorter());
            tokens.erase(tokens.begin() + 1000, tokens.end());
        }
        const int imgCount = m_pClangPlugin->GetImageList(translUnitId).GetImageCount();
        for (int i = 0; i < imgCount; ++i)
            stc->RegisterImage(i, m_pClangPlugin->GetImageList(translUnitId).GetBitmap(i));
        bool isPP = stc->GetLine(line).Strip(wxString::leading).StartsWith(wxT("#"));
        std::set<int> usedWeights;
        for (std::vector<cbCodeCompletionPlugin::CCToken>::iterator tknIt = tokens.begin();
                tknIt != tokens.end(); ++tknIt)
        {
            wxStringVec keywords = m_pClangPlugin->GetKeywords(translUnitId);
            usedWeights.insert(tknIt->weight);
            switch (tknIt->category)
            {
            case tcNone:
                if (isPP)
                    tknIt->category = tcMacroDef;
                else if (std::binary_search(keywords.begin(), keywords.end(), GetActualName(tknIt->name)))
                    tknIt->category = tcLangKeyword;
                break;

            case tcClass:
            case tcCtorPublic:
            case tcDtorPublic:
            case tcFuncPublic:
            case tcVarPublic:
            case tcEnum:
            case tcTypedef:
                // TODO
                //m_Proxy.RefineTokenType(m_TranslUnitId, tknIt->id, tknIt->category);
                break;

            default:
                break;
            }
        }
        // Clang sometimes gives many weight values, which can make completion more difficult
        // because results are less alphabetical. Use a compression map on the lower priority
        // values (higher numbers) to reduce the total number of weights used.
        if (usedWeights.size() > 3)
        {
            std::vector<int> weightsVec(usedWeights.begin(), usedWeights.end());
            std::map<int, int> weightCompr;
            weightCompr[weightsVec[0]] = weightsVec[0];
            weightCompr[weightsVec[1]] = weightsVec[1];
            int factor = (weightsVec.size() > 7 ? 3 : 2);
            for (size_t i = 2; i < weightsVec.size(); ++i)
                weightCompr[weightsVec[i]] = weightsVec[(i - 2) / factor + 2];
            for (std::vector<cbCodeCompletionPlugin::CCToken>::iterator tknIt = tokens.begin();
                    tknIt != tokens.end(); ++tknIt)
            {
                tknIt->weight = weightCompr[tknIt->weight];
            }
        }
    }

    std::cout<<"CodeCompletion finished"<<std::endl;
    return tokens;
}
int IfaceCheckApp::OnRun()
{
    long startTime = wxGetLocalTime();      // for timing purpose

    wxCmdLineParser parser(g_cmdLineDesc, argc, argv);
    parser.SetLogo(
        wxString::Format("wxWidgets Interface checker utility (built %s against %s)",
                         __DATE__, wxVERSION_STRING));

    // make the output more readable:
    wxLog::SetActiveTarget(new IfaceCheckLog);
    wxLog::DisableTimestamp();

    // parse the command line...
    bool ok = true;
    wxString preprocFile;
    switch (parser.Parse())
    {
        case 0:
            if (parser.Found(VERBOSE_SWITCH))
                g_verbose = true;

            // IMPORTANT: parsing #define values must be done _before_ actually
            //            parsing the GCC/doxygen XML files
            if (parser.Found(USE_PREPROCESSOR_OPTION, &preprocFile))
            {
                if (!ParsePreprocessorOutput(preprocFile))
                    return 1;
            }

            // in any case set basic std preprocessor #defines:
            m_doxyInterface.AddPreprocessorValue("NULL", "0");

            // parse the two XML files which contain the real and the doxygen interfaces
            // for wxWidgets API:
            if (!m_gccInterface.Parse(parser.GetParam(0)) ||
                !m_doxyInterface.Parse(parser.GetParam(1)))
                return 1;

            if (parser.Found(DUMP_SWITCH))
            {
                wxLogMessage("Dumping real API to '%s'...", API_DUMP_FILE);
                m_gccInterface.Dump(API_DUMP_FILE);

                wxLogMessage("Dumping interface API to '%s'...", INTERFACE_DUMP_FILE);
                m_doxyInterface.Dump(INTERFACE_DUMP_FILE);
            }
            else
            {
                if (parser.Found(MODIFY_SWITCH))
                    m_modify = true;

                if (parser.Found(PROCESS_ONLY_OPTION, &m_strToMatch))
                {
                    size_t len = m_strToMatch.Len();
                    if (m_strToMatch.StartsWith("\"") &&
                        m_strToMatch.EndsWith("\"") &&
                        len > 2)
                        m_strToMatch = m_strToMatch.Mid(1, len-2);
                }


                ok = Compare();
            }

            PrintStatistics(wxGetLocalTime() - startTime);
            return ok ? 0 : 1;

        default:
            wxPrintf("\nThis utility checks that the interface XML files created by Doxygen are in\n");
            wxPrintf("synch with the real headers (whose contents are extracted by the gcc XML file).\n\n");
            wxPrintf("The 'gccXML' parameter should be the wxapi.xml file created by the 'rungccxml.sh'\n");
            wxPrintf("script which resides in 'utils/ifacecheck'.\n");
            wxPrintf("The 'doxygenXML' parameter should be the index.xml file created by Doxygen\n");
            wxPrintf("for the wxWidgets 'interface' folder.\n\n");
            wxPrintf("Since the gcc XML file does not contain info about #defines, if you use\n");
            wxPrintf("the -%s option, you'll get a smaller number of false warnings.\n",
                     USE_PREPROCESSOR_OPTION);

            // HELP_SWITCH was passed or a syntax error occurred
            return 0;
    }
}
void MyTimer::Notify()
{
	static bool working=false;
	if(working==true)
	{
		return;
	}
	if(Connector::isBusy())
	{
		return;
	}
	working=true;

	wxStandardPaths sp;
	static wxString cfgDir=sp.GetUserDataDir();
	static long starttime=wxGetLocalTime();
	static long startuptime_passed=0;
	static long lastbackuptime=-5*60*1000;
	static long lastversioncheck=starttime;

	if(!wxDir::Exists(cfgDir) )
	{
		wxFileName::Mkdir(cfgDir);
	}

	if(startuptime_passed==0)
	{
		startuptime_passed=atoi(getFile((cfgDir+wxT("/passedtime.cfg") ).ToUTF8().data() ).c_str() );
		startuptime_passed+=atoi(getFile((cfgDir+wxT("/passedtime_new.cfg") ).ToUTF8().data() ).c_str() );
		writestring(nconvert((int)startuptime_passed), (cfgDir+wxT("/passedtime.cfg") ).ToUTF8().data() );
		lastbackuptime=atoi(getFile((cfgDir+wxT("/lastbackuptime.cfg") ).ToUTF8().data() ).c_str() );
		if(lastbackuptime==0)
			lastbackuptime=-5*60*1000;
		std::string update_intv=getFile((cfgDir+wxT("/incr_updateintervall.cfg") ).ToUTF8().data() );
		if(!update_intv.empty())
			incr_update_intervall=atoi(update_intv.c_str());
	}

	long ct=wxGetLocalTime();

	if(ct-lastversioncheck>600 && !displayed_update_info)
	{
		std::string n_version=getFile("version.txt");
		std::string c_version=getFile("curr_version.txt");
		if(n_version.empty())n_version="0";
		if(c_version.empty())c_version="0";

		if( atoi(n_version.c_str())>atoi(c_version.c_str()))
		{
#ifndef wxUSE_TASKBARICON_BALLOONS
			TaskBarBaloon *tbb=new TaskBarBaloon(_("UrBackup: Update verfügbar"), _("Eine neue Version von UrBackup ist verfügbar. Klicken Sie hier um diese zu installieren"));
			tbb->showBaloon(80000);
#else
			tray->BalloonActionUpgrade();
			tray->ShowBalloon(_("UrBackup: Update verfügbar"), _("Eine neue Version von UrBackup ist verfügbar. Klicken Sie hier um diese zu installieren"), 30000, wxICON_INFORMATION);
			displayed_update_info=true;
#endif
		}
		ct=wxGetLocalTime();
		lastversioncheck=ct;
	}

	long passed=( ct-starttime );

	writestring(nconvert((int)passed), (cfgDir+wxT("/passedtime_new.cfg") ).ToUTF8().data() );

	wxString status_text;
	SStatus status=Connector::getStatus();

	if(Connector::hasError() )
	{
		if(icon_type!=4)
		{
			last_status=_("Keine Verbindung zum Backupserver möglich");
			if(tray!=NULL)
				tray->SetIcon(wxIcon(res_path+wxT("backup-bad.")+ico_ext, ico_type), last_status);
			icon_type=4;
		}
		working=false;
		return;
	}

	capa=status.capa;

	int last_icon_type=icon_type;
	bool refresh=false;
	
	if(status.status==wxT("DONE") )
	{
		writestring(nconvert((int)startuptime_passed+(int)passed), (cfgDir+wxT("/lastbackuptime.cfg") ).ToUTF8().data() );
		lastbackuptime=startuptime_passed+passed;
		icon_type=0;
		working_status=0;
		refresh=true;
	}
	else if(status.status==wxT("INCR") )
	{
		status_text+=_("Inkrementelles Backup läuft. ");
		if(!status.pcdone.empty())
		{
			status_text+=status.pcdone;
			status_text+=_("% fertig. ");
		}
		icon_type=1;
		working_status=1;

	}
	else if(status.status==wxT("FULL") )
	{
		status_text+=_("Volles Backup läuft. ");
		if(!status.pcdone.empty())
		{
			status_text+=status.pcdone;
			status_text+=_("% fertig. ");
		}
		icon_type=1;
		working_status=2;
	}
	else if(status.status==wxT("INCRI") )
	{
		status_text+=_("Inkrementelles Image-Backup läuft. ");
		if(!status.pcdone.empty())
		{
			status_text+=status.pcdone;
			status_text+=_("% fertig. ");
		}
		icon_type=1;
		working_status=3;
	}
	else if(status.status==wxT("FULLI") )
	{
		status_text+=_("Volles Image-Backup läuft. ");
		if(!status.pcdone.empty())
		{
			status_text+=status.pcdone;
			status_text+=_("% fertig. ");
		}
		icon_type=1;
		working_status=4;
	}
	else if(startuptime_passed+passed-(long)incr_update_intervall>lastbackuptime)
	{	
		status_text+=_("Kein aktuelles Backup. ");
		icon_type=2;
		working_status=0;
	}
	else
	{
		icon_type=0;
		working_status=0;
	}

	if(!status.lastbackupdate.Trim().empty() )
		status_text+=_("Letztes Backup am ")+status.lastbackupdate;

	if( icon_type<3 && incr_update_done==false)
	{
		unsigned int n_incr_update_intervall=Connector::getIncrUpdateIntervall();
		if(!Connector::hasError() && n_incr_update_intervall!=0)
		{
			incr_update_done=true;
			incr_update_intervall=n_incr_update_intervall;
			writestring(nconvert(incr_update_intervall), (cfgDir+wxT("/incr_updateintervall.cfg") ).ToUTF8().data() );
		}
	}

	if(status.pause && icon_type==1)
	{
		icon_type=3;
	}

	if(icon_type!=last_icon_type || last_status!=status_text || refresh)
	{
		last_status=status_text;
		switch(icon_type)
		{
		case 0:
			if(tray!=NULL)
				tray->SetIcon(wxIcon(res_path+wxT("backup-ok.")+ico_ext, ico_type), status_text);
			if(timer!=NULL)
				timer->Start(60000);
			break;
		case 1:
			if(tray!=NULL)
				tray->SetIcon(wxIcon(res_path+wxT("backup-progress.")+ico_ext, ico_type), status_text);
			if(timer!=NULL)
				timer->Start(10000);
			break;
		case 2:
			if(tray!=NULL)
				tray->SetIcon(wxIcon(res_path+wxT("backup-bad.")+ico_ext, ico_type), status_text);
			if(timer!=NULL)
				timer->Start(60000);
			break;
		case 3:
			if(tray!=NULL)
				tray->SetIcon(wxIcon(res_path+wxT("backup-progress-pause.")+ico_ext, ico_type), status_text);

			if(timer!=NULL)
				timer->Start(60000);
		}
	}

	if(!status.new_server.empty())
	{
#ifndef wxUSE_TASKBARICON_BALLOONS
			TaskBarBaloon *tbb=new TaskBarBaloon(_("UrBackup: Neuer Server"), _("Ein neuer Backup Server wurde gefunden. Hier klicken um diesen zu benutzen"), status.new_server);
			tbb->showBaloon(80000);
#else
			tray->BalloonActionNewServer(status.new_server);
			tray->ShowBalloon(_("UrBackup: Neuer Server"), _("Ein neuer Backup Server wurde gefunden. Hier klicken um diesen zu benutzen"), 80000, wxICON_INFORMATION);
#endif
	}

	working=false;
}
Exemple #16
0
wxString Config::gen_SPA(wxString ip_resolver_url)
{
    CURLcode curl_Res;
    fko_ctx_t ctx;
    fwknop_options_t opts;
    int key_len, res;
    int hmac_str_len = 0;
    short message_type = FKO_CLIENT_TIMEOUT_NAT_ACCESS_MSG;
    short digest_type = FKO_DIGEST_SHA256;
    short hmac_type = FKO_HMAC_SHA256;
    char key_str[129] = {0}, hmac_str[129] = {0};
    char spa_msg[256] = {0};
    char debug_buf[4096] = {0};
    char nat_access_str[25] = {0};

    memset(&opts, 0, sizeof(fwknop_options_t));

    if (this->KEY.IsEmpty())
        return _("Key cannot be blank!");

    wxBusyInfo wait(_("Please wait, working..."));
    if (this->SERVER_PORT.CmpNoCase(wxT("random")) == 0)
    {
        srand((int)wxGetLocalTime());
        this->SERVER_PORT.Empty();
        this->SERVER_PORT << (rand()%55535 + 10000); // do this better, this isn't a horribly good random function
    }
    if (this->ACCESS_IP.CmpNoCase(wxT("Source IP")) == 0)
        this->ACCESS_IP = wxT("0.0.0.0");
    else if (this->ACCESS_IP.CmpNoCase(wxT("Resolve IP")) == 0)
    {
        std::ostringstream oss;
        curl_Res = curl_read(std::string(ip_resolver_url.mb_str()), oss); //Eventually make this a user definable service.
        if (curl_Res == CURLE_OK)
        {
            wxString result_tmp = wxString::FromUTF8(oss.str().c_str());
            wxRegEx findIP( wxT("(([0-9]{1}|[0-9]{2}|[0-1][0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]{1}|[0-9]{2}|[0-1][0-9]{2}|2[0-4][0-9]|25[0-5])"));
            if (!findIP.Matches(result_tmp))
                return _("Unable to resolve our IP!");

            this->ACCESS_IP = findIP.GetMatch(result_tmp);
        } else
            return _("Libcurl returned the error: ") + wxString::FromUTF8(curl_easy_strerror(curl_Res));

    } //end resolve ip

    if (this->KEY_BASE64)
    {
        key_len = fko_base64_decode(this->KEY.mb_str(), (unsigned char *)key_str);
    } else {
        strncpy(key_str, (const char*)this->KEY.mb_str(wxConvUTF8), 128);
        key_len = (int)strlen(key_str);
    }

    if (this->HMAC_BASE64)
    {
        hmac_str_len = fko_base64_decode(this->HMAC.mb_str(), (unsigned char *)hmac_str);
    } else {
        strncpy(hmac_str, (const char*)this->HMAC.mb_str(wxConvUTF8), 128);
        hmac_str_len = (int)strlen(hmac_str);
    }

    if (fko_new(&ctx) != FKO_SUCCESS)
        return _("Could not get new FKO context");

    if (MESS_TYPE.CmpNoCase(wxT("Server Command")) == 0)
    {
        message_type = FKO_COMMAND_MSG;
        if (fko_set_spa_message_type(ctx, message_type) != FKO_SUCCESS)
            return _("Could not set message type");

        snprintf(spa_msg, 256, "%s,%s", (const char*)this->ACCESS_IP.mb_str(wxConvUTF8), (const char*)this->SERVER_CMD.mb_str(wxConvUTF8));
        res = fko_set_spa_message(ctx, spa_msg);
        if (res != FKO_SUCCESS)
            return _("Could not set command message");

    } else {
        if (fko_set_spa_client_timeout(ctx, wxAtoi(this->SERVER_TIMEOUT)) != FKO_SUCCESS)
            return _("Could not set SPA timeout");

        snprintf(spa_msg, 256, "%s,%s", (const char*)this->ACCESS_IP.mb_str(wxConvUTF8), (const char*)this->PORTS.mb_str(wxConvUTF8));
        if (fko_set_spa_message(ctx, spa_msg) != FKO_SUCCESS)
            return _("Could not set SPA Message");

    }
    if (this->LEGACY) { // technically should trim hmac keys
        if (fko_set_spa_encryption_mode(ctx, FKO_ENC_MODE_CBC_LEGACY_IV) != FKO_SUCCESS)
            return _("Could not set Legacy mode.");

    }
    if (!this->HMAC.IsEmpty()){
        if (this->HMAC_TYPE.CmpNoCase(wxT("MD5"))==0)
            hmac_type = FKO_HMAC_MD5;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA1"))==0)
            hmac_type = FKO_HMAC_SHA1;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA256"))==0)
            hmac_type = FKO_HMAC_SHA256;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA384"))==0)
            hmac_type = FKO_HMAC_SHA384;
        else if (this->HMAC_TYPE.CmpNoCase(wxT("SHA512"))==0)
            hmac_type = FKO_HMAC_SHA512;
        if (fko_set_spa_hmac_type(ctx, hmac_type) != FKO_SUCCESS)
            return _("Could not set HMAC type.");

    }
    if (this->MESS_TYPE.CmpNoCase(wxT("Nat Access")) == 0)
    {
        sprintf(nat_access_str, "%s,%s", (const char*)this->NAT_IP.mb_str(wxConvUTF8), (const char*)this->NAT_PORT.mb_str(wxConvUTF8));
        if (fko_set_spa_nat_access(ctx, nat_access_str) != FKO_SUCCESS)
            return _("Could not set nat access string.");

    } else if (this->MESS_TYPE.CmpNoCase(wxT("Local Nat Access")) == 0) {
        message_type = FKO_CLIENT_TIMEOUT_LOCAL_NAT_ACCESS_MSG;
        if (fko_set_spa_message_type(ctx, message_type) != FKO_SUCCESS)
        return _("Chould not set message type");
        sprintf(nat_access_str, "%s,%s", (const char*)this->SERVER_IP.mb_str(wxConvUTF8), (const char*)this->NAT_PORT.mb_str(wxConvUTF8));
        if (fko_set_spa_nat_access(ctx, nat_access_str) != FKO_SUCCESS)
            return _("Could not set nat access string.");
    }
    if (this->DIGEST_TYPE.CmpNoCase(wxT("MD5"))==0)
        digest_type = FKO_DIGEST_MD5;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA1"))==0)
        digest_type = FKO_DIGEST_SHA1;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA256"))==0)
        digest_type = FKO_DIGEST_SHA256;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA384"))==0)
        digest_type = FKO_DIGEST_SHA384;
    else if (this->DIGEST_TYPE.CmpNoCase(wxT("SHA512"))==0)
        digest_type = FKO_DIGEST_SHA512;
    if (fko_set_spa_digest_type(ctx, digest_type) != FKO_SUCCESS)
        return _("Could not set SPA digest type.");

    if (fko_spa_data_final(ctx, key_str, key_len, hmac_str, hmac_str_len) != FKO_SUCCESS)
        return _("Could not generate SPA data.");

    if (fko_get_spa_data(ctx, &opts.spa_data) != FKO_SUCCESS)
        return _("Could not retrieve SPA data.");

    //dump_ctx_to_buffer(ctx, debug_buf, sizeof(debug_buf));

    this->SPA_STRING = wxString::FromUTF8(opts.spa_data);
    return _("Success");
}