Esempio n. 1
0
int bmx_wxgetsinglechoiceindex(BBString * message, BBString * caption, BBArray * choices, wxWindow * parent,
		int x, int y, int centre, int width, int height) {

	if (parent) {
		return wxGetSingleChoiceIndex(wxStringFromBBString(message), wxStringFromBBString(caption), bbStringArrayTowxArrayStr(choices), 
			parent, x, y, static_cast<bool>(centre), width, height);
	} else {
		return wxGetSingleChoiceIndex(wxStringFromBBString(message), wxStringFromBBString(caption), bbStringArrayTowxArrayStr(choices), 
			NULL, x, y, static_cast<bool>(centre), width, height);
	}

}
void SettingsAudioOutput::OnOutputChange(wxCommandEvent& event)
{
	wxTreeItemId selection = m_AudioOutput->GetSelection();
	AudioItemData* data = GetObject(selection);
	if (data && data->type == AudioItemData::AUDIO_NODE)
	{
		int index;
		wxArrayString devs;
		std::vector<wxString> devices = GetRemainingAudioDevices();
		for(unsigned i = 0; i < devices.size(); i++)
			devs.Add(devices[i]);
		devs.Insert(data->name, 0);
		index = wxGetSingleChoiceIndex(_("Change audio device"), _("Change audio device"), devs, this);
		if (index == -1 || index == 0)
			return;
		unsigned channels = m_AudioOutput->GetChildrenCount(selection, false);
		bool error = false;
		for(unsigned i = 0; i < m_DeviceList.size(); i++)
			if (m_DeviceList[i].name == devs[index])
				if (channels > m_DeviceList[i].channels)
					error = true;
		if (error)
		{
			wxMessageBox(_("Too many audio channels configured for the new audio interface") , _("Error"), wxOK | wxICON_ERROR, this);
			return;
		}
		data->name = devs[index];

		UpdateDevice(selection);
	}
	else if (data && data->type == AudioItemData::GROUP_NODE)
	{
		int index;
		std::vector<std::pair<wxString, bool> > groups;
		wxArrayString names;
		groups = GetRemainingAudioGroups(m_AudioOutput->GetItemParent(selection));
		groups.insert(groups.begin(), std::pair<wxString, bool>(data->name, data->left));
		for(unsigned i = 0; i < groups.size(); i++)
			names.Add(wxString::Format(groups[i].second ? _("%s - left") : _("%s - right"), groups[i].first.c_str()));
		index = wxGetSingleChoiceIndex(_("Change audio group"), _("Change audio group"), names, this);
		if (index == -1 || index == 0)
			return;
		data->name = groups[index].first;
		data->left = groups[index].second;
		UpdateVolume(selection, data->volume);
	}
	UpdateButtons();
}
Esempio n. 3
0
wxString GetEncoding(wxString const& filename) {
	agi::charset::CharsetListDetected list;

	try {
		list = agi::charset::DetectAll(from_wx(filename));
	} catch (const agi::charset::UnknownCharset&) {
		/// @todo If the charset is unknown we need to display a complete list of character sets.
	}

	if (list.size() == 1) {
		auto charset = list.begin();
		LOG_I("charset/file") << filename << " (" << charset->second << ")";
		return to_wx(charset->second);
	}

	wxArrayString choices;
	std::string log_choice;

	for (auto const& charset : list) {
		choices.push_back(to_wx(charset.second));
		log_choice.append(" " + charset.second);
	}

	LOG_I("charset/file") << filename << " (" << log_choice << ")";

	int choice = wxGetSingleChoiceIndex(_("Aegisub could not narrow down the character set to a single one.\nPlease pick one below:"),_("Choose character set"),choices);
	if (choice == -1) throw "Canceled";
	return choices[choice];
}
Esempio n. 4
0
void LayerDlg::OnLayerCreate( wxCommandEvent &event )
{
	if (!m_pTerrain)
		return;

	wxArrayString choices;
	choices.Add(_("Abstract (Points with labels)"));
	choices.Add(_("Structure"));
	choices.Add(_("Vegetation"));
	int index = wxGetSingleChoiceIndex(_("Layer type:"), _("Create new layer"), choices, this);
	if (index == 0)
	{
		if (CreateNewAbstractPointLayer(m_pTerrain))
			RefreshTreeContents();
	}
	else if (index == 1)
	{
		// make a new structure layer
		vtStructureLayer *slay = m_pTerrain->NewStructureLayer();
		slay->SetFilename("Untitled.vtst");
		m_pTerrain->SetActiveLayer(slay);
		RefreshTreeContents();
	}
	else if (index == 2)
	{
		// make a new veg layer
		vtVegLayer *vlay = m_pTerrain->NewVegLayer();
		vlay->SetFilename("Untitled.vf");
		m_pTerrain->SetActiveLayer(vlay);
		RefreshTreeContents();
	}
}
Esempio n. 5
0
wxFontEncoding MyFrame::GetEncodingFromUser()
{
    wxArrayString names;
    wxArrayInt encodings;

    const size_t count = wxFontMapper::GetSupportedEncodingsCount();
    names.reserve(count);
    encodings.reserve(count);

    for ( size_t n = 0; n < count; n++ )
    {
        wxFontEncoding enc = wxFontMapper::GetEncoding(n);
        encodings.push_back(enc);
        names.push_back(wxFontMapper::GetEncodingName(enc));
    }

    int i = wxGetSingleChoiceIndex
            (
                wxT("Choose the encoding"),
                SAMPLE_TITLE,
                names,
                this
            );

    return i == -1 ? wxFONTENCODING_SYSTEM : (wxFontEncoding)encodings[i];
}
Esempio n. 6
0
wxFontFamily MyFrame::GetFamilyFromUser()
{
    wxArrayString names;
    wxArrayInt families;

    families.push_back(wxFONTFAMILY_DECORATIVE);
    families.push_back(wxFONTFAMILY_ROMAN);
    families.push_back(wxFONTFAMILY_SCRIPT);
    families.push_back(wxFONTFAMILY_SWISS);
    families.push_back(wxFONTFAMILY_MODERN);
    families.push_back(wxFONTFAMILY_TELETYPE);

    names.push_back("DECORATIVE");
    names.push_back("ROMAN");
    names.push_back("SCRIPT");
    names.push_back("SWISS");
    names.push_back("MODERN");
    names.push_back("TELETYPE");

    int i = wxGetSingleChoiceIndex
            (
                wxT("Choose the family"),
                SAMPLE_TITLE,
                names,
                this
            );

    return i == -1 ? wxFONTFAMILY_DEFAULT : (wxFontFamily)families[i];
}
Esempio n. 7
0
static bool ChooseLanguage(wxString *value)
{
    wxArrayString langs;
    wxArrayString arr;

    {
        wxBusyCursor bcur;
        langs = wxTranslations::Get()->GetAvailableTranslations("poedit");

        arr.push_back(_("(Use default language)"));
        for (auto i : langs)
        {
            auto lang = Language::TryParse(i.ToStdWstring());
            arr.push_back(lang.DisplayNameInItself() + L"  —  " + lang.DisplayName());
        }
    }
    int choice = wxGetSingleChoiceIndex(
            _("Select your preferred language"),
            _("Language selection"),
            arr);
    if ( choice == -1 )
        return false;

    if ( choice == 0 )
        *value = "";
    else
        *value = langs[choice-1];
    return true;
}
Esempio n. 8
0
/// @brief Pick a language 
/// @return 
///
int AegisubLocale::PickLanguage() {
	// Get list
	wxArrayInt langs = GetAvailableLanguages();

	// Check if english is in it, else add it
	if (langs.Index(wxLANGUAGE_ENGLISH) == wxNOT_FOUND) {
		langs.Insert(wxLANGUAGE_ENGLISH,0);
	}

	// Check if user local language is available, if so, make it first
	int user = wxLocale::GetSystemLanguage();
	if (langs.Index(user) != wxNOT_FOUND) {
		langs.Remove(user);
		langs.Insert(user,0);
	}

	// Generate names
	wxArrayString langNames;
	for (size_t i=0;i<langs.Count();i++) {
		langNames.Add(wxLocale::GetLanguageName(langs[i]));
	}

	// Nothing to pick
	if (langs.Count() == 0) return -1;

	// Popup
	int picked = wxGetSingleChoiceIndex(_T("Please choose a language:"),_T("Language"),langNames,NULL,-1,-1,true,300,400);
	if (picked == -1) return -1;
	return langs[picked];
}
Esempio n. 9
0
void BattleRoomTab::OnSetModDefaultPreset( wxCommandEvent& /*unused*/ )
{
	if ( !m_battle ) return;
	wxArrayString choices = m_battle->GetPresetList();
	int result = wxGetSingleChoiceIndex( _( "Pick an existing option set from the list" ), _( "Set game default preset" ), choices );
	if ( result < 0 ) return;
	sett().SetModDefaultPresetName( m_battle->GetHostModName(), choices[result] );
}
Esempio n. 10
0
void BattleRoomTab::OnDeletePreset( wxCommandEvent& /*unused*/ )
{
	if ( !m_battle ) return;
	wxArrayString choices = m_battle->GetPresetList();
	int result = wxGetSingleChoiceIndex( _( "Pick an existing option set from the list" ), _( "Delete preset" ), choices );
	if ( result < 0 ) return;
	m_battle->DeletePreset( choices[result] );
}
void WorkspaceBrowserF::OnSearch(wxCommandEvent& event)
{
	wxString search = m_Search->GetValue();
	if (search.IsEmpty())
		return;

	TokenF* token = 0;
	TokensArrayF result;
    size_t count = FindMatchTokens(search, result);

    size_t i=0;
    while (i < count)
    {
        if (result.Item(i)->m_TokenKind == tkVariable)
        {
            result.RemoveAt(i);
            count--;
        }
        else
        {
            i++;
        }
    }

	if (count == 0)
	{
		cbMessageBox(_("No matches were found: ") + search, _("Search failed"));
		return;
	}
	else if (count == 1)
	{
		token = *result.begin();
	}
	else if (count > 1)
	{
        wxArrayString selections;
        for (size_t i=0; i<count; ++i)
        {
            wxString inf = result.Item(i)->m_DisplayName;;
            wxFileName fn = wxFileName(result.Item(i)->m_Filename);
            inf << _T("::") << result.Item(i)->GetTokenKindString() << _T(", ") << fn.GetFullName() << _T(" : ");
            inf << wxString::Format(_T("%d"), result.Item(i)->m_LineStart);
            selections.Add(inf);
        }
        int sel = wxGetSingleChoiceIndex(_("Please make a selection:"), _("Multiple matches"), selections);
        if (sel == -1)
            return;
        token = result.Item(sel);
	}

    // store the search in the combobox
    if (m_Search->FindString(token->m_DisplayName) == wxNOT_FOUND)
        m_Search->Append(token->m_DisplayName);

    JumpToToken(token);
    m_pBrowserBuilder->SelectItem(token);
}
Esempio n. 12
0
void SettingsAudioOutput::OnOutputAdd(wxCommandEvent& event)
{
	wxTreeItemId selection = m_AudioOutput->GetSelection();
	AudioItemData* data = GetObject(selection);
	if (data && data->type == AudioItemData::AUDIO_NODE)
	{
		unsigned channels = m_AudioOutput->GetChildrenCount(selection, false);
		for(unsigned i = 0; i < m_DeviceList.size(); i++)
			if (m_DeviceList[i].name == data->name)
				if (channels < m_DeviceList[i].channels)
					AddChannelNode(selection, channels);
	}
	else if (data && data->type == AudioItemData::CHANNEL_NODE)
	{
		std::vector<std::pair<wxString, bool> > groups;
		wxArrayString names;
		int index;
		groups = GetRemainingAudioGroups(selection);
		for(unsigned i = 0; i < groups.size(); i++)
			names.Add(wxString::Format(groups[i].second ? _("%s - left") : _("%s - right"), groups[i].first.c_str()));
		index = wxGetSingleChoiceIndex(_("Add new audio group"), _("New audio group"), names, this);
		if (index == -1)
			return;
		wxTreeItemId id = AddGroupNode(selection, groups[index].first, groups[index].second);
		UpdateVolume(id, 0);
	}
	else if (data && data->type == AudioItemData::ROOT_NODE)
	{
		int index;
		wxArrayString devs;
		std::vector<wxString> devices = GetRemainingAudioDevices();
		for(unsigned i = 0; i < devices.size(); i++)
			devs.Add(devices[i]);
		index = wxGetSingleChoiceIndex(_("Add new audio device"), _("New audio device"), devs, this);
		if (index == -1)
			return;
		wxMessageBox(_("Using more than one audio interface is currently not supported.") , _("Warning"), wxOK | wxICON_WARNING, this);
		wxTreeItemId audio = AddDeviceNode(devices[index]);
		AddChannelNode(audio, 0);
	}
	UpdateButtons();
}
Esempio n. 13
0
int wxGetSingleChoiceIndex( const wxString& message,
                            const wxString& caption,
                            int n, const wxString *choices,
                            int initialSelection,
                            wxWindow *parent)
{
    return wxGetSingleChoiceIndex(message, caption, n, choices, parent,
                                  wxDefaultCoord, wxDefaultCoord,
                                  true, wxCHOICE_WIDTH, wxCHOICE_HEIGHT,
                                  initialSelection);
}
Esempio n. 14
0
void CCDebugInfo::OnFindClick(wxCommandEvent& /*event*/)
{
    TokensTree* tokens = m_Parser->GetTokensTree();
    wxString search = txtFilter->GetValue();

    m_Token = 0;

    // first determine if the user entered an ID or a search mask
    long unsigned id;
    if (search.ToULong(&id, 10))
    {
        // easy; ID
        m_Token = tokens->at(id);
    }
    else
    {
        // find all matching tokens
        TokenIdxSet result;
        for (size_t i = 0; i < tokens->size(); ++i)
        {
            Token* token = tokens->at(i);
            if (token && token->m_Name.Matches(search))
                result.insert(i);
        }

        // a single result?
        if (result.size() == 1)
        {
            m_Token = tokens->at(*(result.begin()));
        }
        else
        {
            // fill a list and ask the user which token to display
            wxArrayString arr;
            wxArrayInt intarr;
            for (TokenIdxSet::iterator it = result.begin(); it != result.end(); ++it)
            {
                Token* token = tokens->at(*it);
                arr.Add(token->DisplayName());
                intarr.Add(*it);
            }
            int sel = wxGetSingleChoiceIndex(_("Please make a selection:"), _("Multiple matches"), arr, this);
            if (sel == -1)
                return;

            m_Token = tokens->at(intarr[sel]);
        }
    }

    DisplayTokenInfo();
}
Esempio n. 15
0
bool CMenuEditor::OnEvent(wxPropertyGrid* propGrid,
    wxPGProperty* property,
    wxWindow* /*ctrl*/,
    wxEvent& event) const
{
    CPropertyDescriptionBase* pPropertyDescription = (CPropertyDescriptionBase*)(property->GetClientData());
    if (event.GetEventType() == wxEVT_COMMAND_BUTTON_CLICKED)
    {
        if (pPropertyDescription->GetType() == eRPT_RandomColor)
        {
            CRandomColorPropertyDescription* pRandomColorProperty = down_cast<CRandomColorPropertyDescription*>(pPropertyDescription);
            wxArrayString displayString;
            int nInitSelection = (int)pRandomColorProperty->GetColorType();
            if (!pRandomColorProperty->IsOnlyGradient())
            {
                displayString.Add("color");
                displayString.Add("random color");
            }
            if (!pRandomColorProperty->IsOnlyColor())
            {
                displayString.Add("spline");
                displayString.Add("random spline");
            }
            if (nInitSelection > (int)displayString.size())
            {
                nInitSelection = 0;
            }
            int nSelection = wxGetSingleChoiceIndex("选取类型", "选取类型", displayString, nInitSelection);
            if (nSelection != 0xFFFFFFFF)
            {
                wxPGProperty* pMinProperty = nullptr;
                pRandomColorProperty->SetColorType(ERandomColorType(nSelection));
                ERandomColorType realColorType = pRandomColorProperty->GetColorType();// may not be the same to nSelection.
                wxPGProperty* pMaxProperty = pRandomColorProperty->CreateRandomColorProperty(realColorType, pMinProperty);
                property->DeleteChildren();
                if (pMinProperty)
                {
                    property->InsertChild(-1, pMinProperty);
                }
                property->InsertChild(-1, pMaxProperty);
                propGrid->RefreshProperty(property);
                wxVariant tmp((int)realColorType);
                pRandomColorProperty->SetValue(tmp);
            }
        }
    }
    return true;
}
Esempio n. 16
0
int wxGetSingleChoiceIndex( const wxString& message,
                            const wxString& caption,
                            const wxArrayString& aChoices,
                            wxWindow *parent,
                            int x, int y,
                            bool centre,
                            int width, int height)
{
    wxString *choices;
    int n = ConvertWXArrayToC(aChoices, &choices);
    int res = wxGetSingleChoiceIndex(message, caption, n, choices, parent,
                                     x, y, centre, width, height);
    delete [] choices;

    return res;
}
Esempio n. 17
0
void PreferencesDialog::OnTMAddLang(wxCommandEvent&)
{
    wxArrayString lngs;
    int index;

    for (const LanguageStruct *i = isoLanguages; i->lang != NULL; i++)
        lngs.Add(wxString(i->iso) + _T(" (") + i->lang + _T(")"));
    index = wxGetSingleChoiceIndex(_("Select language"),
                                   _("Please select language ISO code:"),
                                   lngs, this);
    if (index != -1)
    {
        wxArrayString a;
        XRCCTRL(*this, "tm_langs", wxEditableListBox)->GetStrings(a);
        a.Add(isoLanguages[index].iso);
        XRCCTRL(*this, "tm_langs", wxEditableListBox)->SetStrings(a);
    }
}
Esempio n. 18
0
bool Camera_SBIGRotatorClass::Connect(const wxString& camId)
{
    bool bError = false;

    try
    {
        wxString raAngle = wxGetTextFromUser(_("Enter RA Angle (in degrees)"),_("RA angle"), _T("0.0"));
        double temp;

        if (raAngle.length() == 0 || !raAngle.ToDouble(&temp))
        {
            throw ERROR_INFO("invalid raAngle");
        }

        m_raAngle = temp/180.0*M_PI;

        wxArrayString choices;

        choices.Add(wxString::Format("Unmirrored (%.2f)", temp - 90));
        choices.Add(wxString::Format("Mirrored (%.2f)", temp + 90));

        int idx = wxGetSingleChoiceIndex(_("Choose Dec Angle"), _("Dec Angle"),
                                              choices);

        m_mirror = (idx == 1);

        m_pSubcamera = new Camera_SBIGClass();

        bError = m_pSubcamera->Connect(camId);
        Connected = m_pSubcamera->Connected;

        FullSize = m_pSubcamera->FullSize;
        m_hasGuideOutput = m_pSubcamera->ST4HasGuideOutput();
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);

        bError = true;
    }

    return bError;
}
Esempio n. 19
0
/// @brief Ask user for which track he wants to load
/// @param TrackList	A std::map with the track numbers as keys and codec names as values
/// @param Type			The track type to ask about
/// @return				Returns the track number chosen (an integer >= 0) on success, or a negative integer if the user cancelled.
int FFmpegSourceProvider::AskForTrackSelection(const std::map<int, std::string> &TrackList, FFMS_TrackType Type) {
	std::vector<int> TrackNumbers;
	wxArrayString Choices;

	for (auto const& track : TrackList) {
		Choices.Add(wxString::Format(_("Track %02d: %s"), track.first, to_wx(track.second)));
		TrackNumbers.push_back(track.first);
	}

	int Choice = wxGetSingleChoiceIndex(
		Type == FFMS_TYPE_VIDEO ? _("Multiple video tracks detected, please choose the one you wish to load:") : _("Multiple audio tracks detected, please choose the one you wish to load:"),
		Type == FFMS_TYPE_VIDEO ? _("Choose video track") : _("Choose audio track"),
		Choices);

	if (Choice < 0)
		return Choice;
	else
		return TrackNumbers[Choice];
}
Esempio n. 20
0
bool wxExtHelpController::KeywordSearch(const wxString& k,
                                   wxHelpSearchMode WXUNUSED(mode))
{
   if (! m_NumOfEntries)
      return false;

   wxString *choices = new wxString[m_NumOfEntries];
   wxString *urls = new wxString[m_NumOfEntries];

   int          idx = 0;
   bool         rc = false;
   bool         showAll = k.empty();

   wxList::compatibility_iterator node = m_MapList->GetFirst();

   {
        // display a busy cursor
        wxBusyCursor b;
        wxString compA, compB;
        wxExtHelpMapEntry *entry;

        // we compare case insensitive
        if (! showAll)
        {
            compA = k;
            compA.LowerCase();
        }

        while (node)
        {
            entry = (wxExtHelpMapEntry *)node->GetData();
            compB = entry->doc;

            bool testTarget = ! compB.empty();
            if (testTarget && ! showAll)
            {
                compB.LowerCase();
                testTarget = compB.Contains(compA);
            }

            if (testTarget)
            {
                urls[idx] = entry->url;
                // doesn't work:
                // choices[idx] = (**i).doc.Contains((**i).doc.Before(WXEXTHELP_COMMENTCHAR));
                //if (choices[idx].empty()) // didn't contain the ';'
                //   choices[idx] = (**i).doc;
                choices[idx] = wxEmptyString;
                for (int j=0; ; j++)
                {
                    wxChar targetChar = entry->doc.c_str()[j];
                    if ((targetChar == 0) || (targetChar == WXEXTHELP_COMMENTCHAR))
                        break;

                    choices[idx] << targetChar;
                }

                idx++;
            }

            node = node->GetNext();
        }
    }

    switch (idx)
    {
    case 0:
        wxMessageBox(_("No entries found."));
        break;

    case 1:
        rc = DisplayHelp(urls[0]);
        break;

    default:
        idx = wxGetSingleChoiceIndex(
            showAll ? _("Help Index") : _("Relevant entries:"),
            showAll ? _("Help Index") : _("Entries found"),
            idx, choices);
        if (idx >= 0)
            rc = DisplayHelp(urls[idx]);
        break;
    }

    delete [] urls;
    delete [] choices;

    return rc;
}
Esempio n. 21
0
/* GfxEntryPanel::handleAction
 * Handles the action [id]. Returns true if the action was handled,
 * false otherwise
 *******************************************************************/
bool GfxEntryPanel::handleAction(string id)
{
	// Don't handle actions if hidden
	if (!isActivePanel())
		return false;

	// We're only interested in "pgfx_" actions
	if (!id.StartsWith("pgfx_"))
		return false;

	// Mirror
	if (id == "pgfx_mirror")
	{
		// Mirror X
		getImage()->mirror(false);

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Flip
	else if (id == "pgfx_flip")
	{
		// Mirror Y
		getImage()->mirror(true);

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Rotate
	else if (id == "pgfx_rotate")
	{
		// Prompt for rotation angle
		string angles[] = { "90", "180", "270" };
		int choice = wxGetSingleChoiceIndex("Select rotation angle", "Rotate", 3, angles, 0);

		// Rotate image
		switch (choice)
		{
		case 0:
			getImage()->rotate(90);
			break;
		case 1:
			getImage()->rotate(180);
			break;
		case 2:
			getImage()->rotate(270);
			break;
		default: break;
		}

		// Update UI
		gfx_canvas->updateImageTexture();
		gfx_canvas->Refresh();

		// Update variables
		image_data_modified = true;
		setModified();
	}

	// Translate
	else if (id == "pgfx_translate")
	{
		// Create translation editor dialog
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		TranslationEditorDialog ted(theMainWindow, pal, " Colour Remap", gfx_canvas->getImage());

		// Create translation to edit
		ted.openTranslation(prev_translation);

		// Show the dialog
		if (ted.ShowModal() == wxID_OK)
		{
			// Apply translation to image
			getImage()->applyTranslation(&ted.getTranslation(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			gfx_canvas->updateImageTexture();
			setModified();
			prev_translation.copy(ted.getTranslation());
		}
	}

	// Colourise
	else if (id == "pgfx_colourise")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxColouriseDialog gcd(theMainWindow, entry, pal);
		gcd.setColour(last_colour);

		// Show colourise dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// Colourise image
			getImage()->colourise(gcd.getColour(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			Refresh();
			setModified();
		}
		rgba_t gcdcol = gcd.getColour();
		last_colour = S_FMT("RGB(%d, %d, %d)", gcdcol.r, gcdcol.g, gcdcol.b);
	}

	// Tint
	else if (id == "pgfx_tint")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxTintDialog gtd(theMainWindow, entry, pal);
		gtd.setValues(last_tint_colour, last_tint_amount);

		// Show tint dialog
		if (gtd.ShowModal() == wxID_OK)
		{
			// Tint image
			getImage()->tint(gtd.getColour(), gtd.getAmount(), pal);

			// Update UI
			gfx_canvas->updateImageTexture();
			gfx_canvas->Refresh();

			// Update variables
			image_data_modified = true;
			Refresh();
			setModified();
		}
		rgba_t gtdcol = gtd.getColour();
		last_tint_colour = S_FMT("RGB(%d, %d, %d)", gtdcol.r, gtdcol.g, gtdcol.b);
		last_tint_amount = (int)(gtd.getAmount() * 100.0);
	}

	// Crop
	else if (id == "pgfx_crop")
	{
		Palette8bit* pal = theMainWindow->getPaletteChooser()->getSelectedPalette();
		GfxCropDialog gcd(theMainWindow, entry, pal);

		// Show crop dialog
		if (gcd.ShowModal() == wxID_OK)
		{
			// stuff
		}
	}

	// alPh/tRNS
	else if (id == "pgfx_alph" || id == "pgfx_trns")
	{
		setModified();
		Refresh();
	}

	// Optimize PNG
	else if (id == "pgfx_pngopt")
	{
		// This is a special case. If we set the entry as modified, SLADE will prompt
		// to save it, rewriting the entry and cancelling the optimization done...
		if (EntryOperations::optimizePNG(entry))
			setModified(false);
		else
			wxMessageBox("Warning: Couldn't optimize this image, check console log for info", "Warning", wxOK|wxCENTRE|wxICON_WARNING);
		Refresh();
	}

	// Extract all
	else if (id == "pgfx_extract")
	{
		extractAll();
	}

	// Convert
	else if (id == "pgfx_convert")
	{
		GfxConvDialog gcd(theMainWindow);
		gcd.CenterOnParent();
		gcd.openEntry(entry);

		gcd.ShowModal();

		if (gcd.itemModified(0))
		{
			// Get image and conversion info
			SImage* image = gcd.getItemImage(0);
			SIFormat* format = gcd.getItemFormat(0);

			// Write converted image back to entry
			format->saveImage(*image, entry_data, gcd.getItemPalette(0));
			// This makes the "save" button (and the setModified stuff) redundant and confusing!
			// The alternative is to save to entry effectively (uncomment the importMemChunk line)
			// but remove the setModified and image_data_modified lines, and add a call to refresh
			// to get the PNG tRNS status back in sync.
			//entry->importMemChunk(entry_data);
			image_data_modified = true;
			setModified();

			// Fix tRNS status if we converted to paletted PNG
			int MENU_GFXEP_PNGOPT = theApp->getAction("pgfx_pngopt")->getWxId();
			int MENU_GFXEP_ALPH = theApp->getAction("pgfx_alph")->getWxId();
			int MENU_GFXEP_TRNS = theApp->getAction("pgfx_trns")->getWxId();
			int MENU_ARCHGFX_EXPORTPNG = theApp->getAction("arch_gfx_exportpng")->getWxId();
			if (format->getName() == "PNG")
			{
				ArchiveEntry temp;
				temp.importMemChunk(entry_data);
				temp.setType(EntryType::getType("png"));
				menu_custom->Enable(MENU_GFXEP_ALPH, true);
				menu_custom->Enable(MENU_GFXEP_TRNS, true);
				menu_custom->Check(MENU_GFXEP_TRNS, EntryOperations::gettRNSChunk(&temp));
				menu_custom->Enable(MENU_ARCHGFX_EXPORTPNG, false);
				menu_custom->Enable(MENU_GFXEP_PNGOPT, true);
				toolbar->enableGroup("PNG", true);
			}
			else
			{
				menu_custom->Enable(MENU_GFXEP_ALPH, false);
				menu_custom->Enable(MENU_GFXEP_TRNS, false);
				menu_custom->Enable(MENU_ARCHGFX_EXPORTPNG, true);
				menu_custom->Enable(MENU_GFXEP_PNGOPT, false);
				toolbar->enableGroup("PNG", false);
			}

			// Refresh
			getImage()->open(entry_data, 0, format->getId());
			gfx_canvas->Refresh();
		}
	}

	// Unknown action
	else
		return false;

	// Action handled
	return true;
}
Esempio n. 22
0
static void DumpFASTA(bool isA2M, const BlockMultipleAlignment *alignment,
    const vector < int >& rowOrder,
    BlockMultipleAlignment::eUnalignedJustification justification, CNcbiOstream& os)
{
    // do whole alignment for now
    unsigned int firstCol = 0, lastCol = alignment->AlignmentWidth() - 1, nColumns = 70;
    if (lastCol >= alignment->AlignmentWidth() || firstCol > lastCol || nColumns < 1) {
        ERRORMSG("DumpFASTA() - nonsensical display region parameters");
        return;
    }

    // first fill out ids
    typedef map < const MoleculeIdentifier * , list < string > > IDMap;
    IDMap idMap;
    unsigned int row;
    bool anyRepeat = false;

    for (row=0; row<alignment->NRows(); ++row) {
        const Sequence *seq = alignment->GetSequenceOfRow(row);
        list < string >& titleList = idMap[seq->identifier];
        CNcbiOstrstream oss;
        oss << '>';

        if (titleList.size() == 0) {

            // create full title line for first instance of this sequence
            CBioseq::TId::const_iterator i, ie = seq->bioseqASN->GetId().end();
            for (i=seq->bioseqASN->GetId().begin(); i!=ie; ++i) {
                if (i != seq->bioseqASN->GetId().begin())
                    oss << '|';
                oss << (*i)->AsFastaString();
            }
            string descr = seq->GetDescription();
            if (descr.size() > 0)
                oss << ' ' << descr;

        } else {
            // add repeat id
            oss << "lcl|instance #" << (titleList.size() + 1) << " of " << seq->identifier->ToString();
            anyRepeat = true;
        }

        oss << '\n';
        titleList.resize(titleList.size() + 1);
        titleList.back() = (string) CNcbiOstrstreamToString(oss);
    }

    static const int eAllRepeats=0, eFakeRepeatIDs=1, eNoRepeats=2;
    int choice = eAllRepeats;

    if (anyRepeat) {
        wxArrayString choices;
        choices.Add("Include all repeats with normal IDs");
        choices.Add("Include all repeats, but use unique IDs");
        choices.Add("Include no repeated sequences");
        choice = wxGetSingleChoiceIndex("How do you want to handle repeated sequences?",
            "Choose repeat type", choices);
        if (choice < 0) return; // cancelled
    }

    // output each alignment row (in order of the display)
    unsigned int paragraphStart, nParags = 0, i;
    char ch;
    Vector color, bgColor;
    bool highlighted, drawBG;
    for (row=0; row<alignment->NRows(); ++row) {
        const Sequence *seq = alignment->GetSequenceOfRow(rowOrder[row]);

        // output title
        list < string >& titleList = idMap[seq->identifier];
        if (choice == eAllRepeats) {
            os << titleList.front();    // use full id
        } else if (choice == eFakeRepeatIDs) {
            os << titleList.front();
            titleList.pop_front();      // move to next (fake) id
        } else if (choice == eNoRepeats) {
            if (titleList.size() > 0) {
                os << titleList.front();
                titleList.clear();      // remove all ids after first instance
            } else {
                continue;
            }
        }

        // split alignment up into "paragraphs", each with nColumns
        for (paragraphStart=0; (firstCol+paragraphStart)<=lastCol; paragraphStart+=nColumns, ++nParags) {
            for (i=0; i<nColumns && (firstCol+paragraphStart+i)<=lastCol; ++i) {
                if (alignment->GetCharacterTraitsAt(firstCol+paragraphStart+i, rowOrder[row], justification,
                        &ch, &color, &highlighted, &drawBG, &bgColor)) {
                    if (ch == '~')
                        os << (isA2M ? '.' : '-');
                    else
                        os << (isA2M ? ch : (char) toupper((unsigned char) ch));
                } else
                    ERRORMSG("GetCharacterTraitsAt failed!");
            }
            os << '\n';
        }
    }
}
Esempio n. 23
0
bool Camera_QHY::Connect(const wxString& camId)
{
    if (QHYSDKInit())
    {
        wxMessageBox(_("Failed to initialize QHY SDK"));
        return true;
    }

    int num_cams = ScanQHYCCD();
    std::vector<std::string> camids;

    for (int i = 0; i < num_cams; i++)
    {
        char camid[32] = "";
        GetQHYCCDId(i, camid);
        bool st4 = false;
        qhyccd_handle *h = OpenQHYCCD(camid);
        if (h)
        {
            uint32_t ret = IsQHYCCDControlAvailable(h, CONTROL_ST4PORT);
            if (ret == QHYCCD_SUCCESS)
                st4 = true;
                //CloseQHYCCD(h); // CloseQHYCCD() would proform a reset, so the other software that use QHY camera would be impacted.
                                  // Do not call this,would not cause memory leak.The SDk has already process this.
        }
        Debug.Write(wxString::Format("QHY cam [%d] %s avail %s st4 %s\n", i, camid, h ? "Yes" : "No", st4 ? "Yes" : "No"));
        if (st4)
            camids.push_back(camid);
    }

    if (camids.size() == 0)
    {
        wxMessageBox(_("No compatible QHY cameras found"));
        return true;
    }

    std::string camid;

    if (camids.size() > 1)
    {
        wxArrayString names;
        int n = 1;
        for (auto it = camids.begin(); it != camids.end(); ++it, ++n)
            names.Add(wxString::Format("%d: %s", n, *it));

        int i = wxGetSingleChoiceIndex(_("Select QHY camera"), _("Camera choice"), names);
        if (i == -1)
            return true;
        camid = camids[i];
    }
    else
        camid = camids[0];

    char *s = new char[camid.length() + 1];
    memcpy(s, camid.c_str(), camid.length() + 1);
    m_camhandle = OpenQHYCCD(s);
    delete[] s;

    Name = camid;

    if (!m_camhandle)
    {
        wxMessageBox(_("Failed to connect to camera"));
        return true;
    }

    // before calling InitQHYCCD() we must call SetQHYCCDStreamMode(camhandle, 0 or 1)
    //   0: single frame mode  
    //   1: live frame mode 
    uint32_t ret = SetQHYCCDStreamMode(m_camhandle, 0);
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("SetQHYCCDStreamMode failed"));
        return true;
    }

    ret = InitQHYCCD(m_camhandle);
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("Init camera failed"));
        return true;
    }

    ret = GetQHYCCDParamMinMaxStep(m_camhandle, CONTROL_GAIN, &m_gainMin, &m_gainMax, &m_gainStep);
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("Failed to get gain range"));
        return true;
    }

    double chipw, chiph, pixelw, pixelh;
    uint32_t imagew, imageh, bpp;
    ret = GetQHYCCDChipInfo(m_camhandle, &chipw, &chiph, &imagew, &imageh, &pixelw, &pixelh, &bpp);
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("Failed to get camera chip info"));
        return true;
    }

    int bayer = IsQHYCCDControlAvailable(m_camhandle, CAM_COLOR);
    Debug.Write(wxString::Format("QHY: cam reports bayer type %d\n", bayer));

    Color = false;
    switch ((BAYER_ID)bayer) {
    case BAYER_GB:
    case BAYER_GR:
    case BAYER_BG:
    case BAYER_RG:
        Color = true;
    }

    // check bin modes
    CONTROL_ID modes[] = { CAM_BIN2X2MODE, CAM_BIN3X3MODE, CAM_BIN4X4MODE, };
    int bin[] = { 2, 3, 4, };
    int maxBin = 1;
    for (int i = 0; i < WXSIZEOF(modes); i++)
    {
        ret = IsQHYCCDControlAvailable(m_camhandle, modes[i]);
#if 0
        // FIXME- IsQHYCCDControlAvailable is supposed to return QHYCCD_ERROR_NOTSUPPORT for a
        // bin mode that is not supported, but in fact it returns QHYCCD_ERROR, so we cannot
        // distinguish "not supported" from "error".
        if (ret != QHYCCD_SUCCESS && ret != QHYCCD_ERROR_NOTSUPPORT)
        {
            CloseQHYCCD(m_camhandle);
            m_camhandle = 0;
            wxMessageBox(_("Failed to get camera bin info"));
            return true;
        }
#endif
        if (ret == QHYCCD_SUCCESS)
            maxBin = bin[i];
        else
            break;
    }
    Debug.Write(wxString::Format("QHY: max binning = %d\n", maxBin));
    MaxBinning = maxBin;
    if (Binning > MaxBinning)
        Binning = MaxBinning;

    Debug.Write(wxString::Format("QHY: call SetQHYCCDBinMode bin = %d\n", Binning));
    ret = SetQHYCCDBinMode(m_camhandle, Binning, Binning);
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("Failed to set camera binning"));
        return true;
    }
    m_curBin = Binning;

    m_maxSize = wxSize(imagew, imageh);
    FullSize = wxSize(imagew / Binning, imageh / Binning);

    delete[] RawBuffer;
    size_t size = GetQHYCCDMemLength(m_camhandle);
    RawBuffer = new unsigned char[size];

    m_devicePixelSize = sqrt(pixelw * pixelh);

    m_curGain = -1;
    m_curExposure = -1;
    m_roi = wxRect(0, 0, FullSize.GetWidth(), FullSize.GetHeight());  // binned coordinates

    Debug.Write(wxString::Format("QHY: call SetQHYCCDResolution roi = %d,%d\n", m_roi.width, m_roi.height));
    ret = SetQHYCCDResolution(m_camhandle, 0, 0, m_roi.GetWidth(), m_roi.GetHeight());
    if (ret != QHYCCD_SUCCESS)
    {
        CloseQHYCCD(m_camhandle);
        m_camhandle = 0;
        wxMessageBox(_("Init camera failed"));
        return true;
    }

    Debug.Write(wxString::Format("QHY: connect done\n"));
    Connected = true;
    return false;
}
Esempio n. 24
0
bool ObjectsPropgridHelper::OnPropertySelected(gd::Object * object, gd::Layout * layout, wxPropertyGridEvent& event)
{
    if ( !grid || !object ) return false;

    //Check if the object is global
    bool globalObject = false;
    for (std::size_t i = 0;i<project.GetObjectsCount();++i)
    {
        if ( &project.GetObject(i) == object )
        {
            globalObject = true;
            break;
        }
    }

    if ( event.GetColumn() == 1) //Manage button-like properties
    {
        if ( event.GetPropertyName() == _("Edit") )
        {
            object->EditObject(grid, project, mainFrameWrapper);
            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnObjectEdited(project, globalObject ? NULL : layout, *object);

            //Reload resources : Do not forget to switch the working directory.
            wxString oldWorkingDir = wxGetCwd();
            if ( wxDirExists(wxFileName::FileName(project.GetProjectFile()).GetPath()))
                wxSetWorkingDirectory(wxFileName::FileName(project.GetProjectFile()).GetPath());

            if (layout) object->LoadResources(project, *layout);

            wxSetWorkingDirectory(oldWorkingDir);
        }
        else if ( event.GetPropertyName() == _("Help"))
        {
            auto metadata = gd::MetadataProvider::GetObjectMetadata(project.GetCurrentPlatform(),
                object->GetType());

            gd::HelpFileAccess::Get()->OpenPage(metadata.GetHelpUrl());
        }
        else if ( event.GetPropertyName() == _("Variables") )
        {
            gd::ChooseVariableDialog dialog(grid, object->GetVariables(), true);
            dialog.SetAssociatedObject(&project, layout, object);
            if ( dialog.ShowModal() == 1 )
            {
                for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                    project.GetUsedPlatforms()[j]->GetChangesNotifier().OnObjectVariablesChanged(project, globalObject ? NULL : layout, *object);

                //Update the grid:
                if ( grid->GetProperty("OBJECT_VARIABLES_CATEGORY") != NULL)
                    grid->SetPropertyLabel("OBJECT_VARIABLES_CATEGORY",
                        _("Object variables") + " (" + gd::String::From(object->GetVariables().Count()) + ")");
            }
        }
        else if ( event.GetPropertyName() == "AUTO_ADD" )
        {
            return gd::ChooseBehaviorTypeDialog::ChooseAndAddBehaviorToObject(grid, project,
                object, layout, globalObject);
        }
        else if ( event.GetPropertyName() == "AUTO_REMOVE" )
        {
            //Create behavior array
            wxArrayString behaviorsStr;

            //Fill array
            std::vector <gd::String> behaviors = object->GetAllBehaviorNames();
            for (std::size_t i = 0;i<behaviors.size();++i)
                behaviorsStr.Add(object->GetBehavior(behaviors[i]).GetName());

            int selection = wxGetSingleChoiceIndex(_("Choose the behavior to delete"), _("Choose the behavior to delete"), behaviorsStr);
            if ( selection == -1 ) return false;

            object->RemoveBehavior(behaviors[selection]);
            UpdateBehaviorsSharedData(project, globalObject ? NULL : layout);

            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorDeleted(project, globalObject ? NULL : layout, *object, behaviors[selection]);

            return true;
        }
        else if ( event.GetPropertyName().substr(0,12) == "AUTO_RENAME:" )
        {
            event.Veto();
            gd::String oldName = event.GetPropertyName().substr(12);
            if ( !object->HasBehaviorNamed(oldName)) return true;

            gd::Behavior & behavior = object->GetBehavior(oldName);

            gd::String newName = wxGetTextFromUser(_("Enter a new name for the behavior"), _("Rename a behavior"), behavior.GetName());
            if ( newName == behavior.GetName() || object->HasBehaviorNamed(newName) || newName.empty() ) return false;

            object->RenameBehavior(oldName, newName);
            UpdateBehaviorsSharedData(project, globalObject ? NULL : layout);

            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorRenamed(project, globalObject ? NULL : layout, *object, behavior, oldName);

            return true;
        }
        else if ( event.GetPropertyName().substr(0,5) == "AUTO:" )
        {
            event.Veto();
            gd::String autoName = event.GetPropertyName().substr(5);
            if ( !object->HasBehaviorNamed(autoName)) return true;

            gd::Behavior & behavior = object->GetBehavior(autoName);

            behavior.EditBehavior(grid, project, layout, mainFrameWrapper); //EditBehavior always need a valid layout!
            for ( std::size_t j = 0; j < project.GetUsedPlatforms().size();++j)
                project.GetUsedPlatforms()[j]->GetChangesNotifier().OnBehaviorEdited(project, globalObject ? NULL : layout, *object, behavior);
        }
    }

    return false;
}
Esempio n. 25
0
bool MyFrame::DoEnumerateFamilies(bool fixedWidthOnly,
                                  wxFontEncoding encoding,
                                  bool silent)
{
    MyFontEnumerator fontEnumerator;

    fontEnumerator.EnumerateFacenames(encoding, fixedWidthOnly);

    if ( fontEnumerator.GotAny() )
    {
        int nFacenames = fontEnumerator.GetFacenames().GetCount();
        if ( !silent )
        {
            wxLogStatus(this, wxT("Found %d %sfonts"),
                        nFacenames, fixedWidthOnly ? wxT("fixed width ") : wxT(""));
        }

        wxString facename;

        if ( silent )
        {
            // choose the first
            facename = fontEnumerator.GetFacenames().Item(0);
        }
        else
        {
            // let the user choose
            wxString *facenames = new wxString[nFacenames];
            int n;
            for ( n = 0; n < nFacenames; n++ )
                facenames[n] = fontEnumerator.GetFacenames().Item(n);

            n = wxGetSingleChoiceIndex
                (
                    wxT("Choose a facename"),
                    SAMPLE_TITLE,
                    nFacenames,
                    facenames,
                    this
                );

            if ( n != -1 )
                facename = facenames[n];

            delete [] facenames;
        }

        if ( !facename.empty() )
        {
            wxFont font(wxFontInfo().FaceName(facename).Encoding(encoding));

            DoChangeFont(font);
        }

        return true;
    }
    else if ( !silent )
    {
        wxLogWarning(wxT("No such fonts found."));
    }

    return false;
}
int internationalization::get_wx_locale_number_from_choice_dialog()
{
    // I will initialize it to zero for wxLANGUAGE_DEFAULT
    int selected_locale_wx_number = 0;
    
    // These need to be inside the class in order to get translated at runtime
    // [if was outside class, then lookup is before we set the locale]
    const wxString plkr_languages[] = { _( "[System default]" ),
                                        _( "Catalan" ),
                                        _( "Czech" ),
                                        _( "Danish" ),
                                        _( "German" ),
                                        _( "Spanish" ),
                                        _( "English" ),
                                        _( "English (US)" ),
                                        _( "Faeroese" ),
                                        _( "French" ),
                                        _( "Italian" ),
                                        _( "Japanese" ),
                                        _( "Dutch" ),
                                        _( "Polish" ),
                                        _( "Russian" )
                                      };
    
    /*! \test I don't think this is needed anymore, as wx233 is supposed to not stop
       when close top frame while still inside OnInit()
     */
    // Usual wxWindows behaviour is to kill the application when the top window
    // is closed. This prevents that behavior, until we are done showing this popup.                         
    wxGetApp().SetExitOnFrameDelete( FALSE );    
    
    // Show the multiple choice box, returning the index of the number they selected
    int selected_language_index = wxGetSingleChoiceIndex( _( "Please choose language:" ),
                                                          _( "Language" ), 
                                                          WXSIZEOF( plkr_languages ), 
                                                          plkr_languages );
                                                          
    // Put application's behaviour back to ending on closing the top frame.
    wxGetApp().SetExitOnFrameDelete( TRUE );    
   
    // Set the wxLocale language to the one they selected
    switch ( selected_language_index ) 
    {    
        case 0  : selected_locale_wx_number = wxLANGUAGE_DEFAULT;     break;
		case 1  : selected_locale_wx_number = wxLANGUAGE_CATALAN;     break;
        case 2  : selected_locale_wx_number = wxLANGUAGE_CZECH;       break;
        case 3  : selected_locale_wx_number = wxLANGUAGE_DANISH;      break;
        case 4  : selected_locale_wx_number = wxLANGUAGE_GERMAN;      break;
        case 5  : selected_locale_wx_number = wxLANGUAGE_SPANISH;     break;      
        case 6  : selected_locale_wx_number = wxLANGUAGE_ENGLISH;     break;
        case 7  : selected_locale_wx_number = wxLANGUAGE_ENGLISH_US;  break;
        case 8  : selected_locale_wx_number = wxLANGUAGE_FAEROESE;    break;
        case 9  : selected_locale_wx_number = wxLANGUAGE_FRENCH;      break;
        case 10 : selected_locale_wx_number = wxLANGUAGE_ITALIAN;     break;
        case 11 : selected_locale_wx_number = wxLANGUAGE_JAPANESE;    break;
        case 12 : selected_locale_wx_number = wxLANGUAGE_DUTCH;       break;
        case 13 : selected_locale_wx_number = wxLANGUAGE_POLISH;      break;
        case 14 : selected_locale_wx_number = wxLANGUAGE_RUSSIAN;     break; 
    }
    
    return selected_locale_wx_number;

}
Esempio n. 27
0
void mmStockDialog::OnHistoryDownloadButton(wxCommandEvent& /*event*/)
{
    /*
    Example stock history download:
    https://code.google.com/p/yahoo-finance-managed/wiki/csvHistQuotesDownload
    */

    if (m_stock->SYMBOL.IsEmpty())
        return;

    const wxDateTime& StartDate = Model_Stock::PURCHASEDATE(m_stock);
    wxDateTime EndDate = wxDate::Today();
    const wxTimeSpan time = EndDate - StartDate;
    long intervalMonths = EndDate.GetMonth() - StartDate.GetMonth()
        + 12 * (EndDate.GetYear() - StartDate.GetYear())
        - (EndDate.GetDay() < StartDate.GetDay());

    //Define frequency
    enum { DAILY, WEEKLY, MONTHLY };
    wxArrayString FreqStrs;
    FreqStrs.Add(_("Days"));
    FreqStrs.Add(_("Weeks"));
    if (intervalMonths > 0) FreqStrs.Add(_("Months"));

    int freq = wxGetSingleChoiceIndex(_("Specify type frequency of stock history")
        , _("Stock History Update"), FreqStrs);

    long interval = 0;
    switch (freq)
    {
    case DAILY: interval = time.GetDays(); break;
    case WEEKLY: interval = time.GetWeeks(); break;
    case MONTHLY: interval = intervalMonths; break;
    default: return;
    }

    int nrPrices = (int) wxGetNumberFromUser(_("Specify how many stock history prices download from purchase date")
        , wxString::Format(_("Number of %s:"), FreqStrs.Item(freq).Lower()), _("Stock History Update")
        , interval, 1L, 9999L, this, wxDefaultPosition);

    if (nrPrices <= 0)
    {
        mmErrorDialogs::MessageInvalid(this, FreqStrs[freq]);
        return;
    }
    else
    {
        switch (freq)
        {
        case DAILY: EndDate = wxDate(StartDate).Add(wxDateSpan::Days(nrPrices)); break;
        case WEEKLY: EndDate = wxDate(StartDate).Add(wxDateSpan::Weeks(nrPrices)); break;
        case MONTHLY: EndDate = wxDate(StartDate).Add(wxDateSpan::Months(nrPrices)); break;
        default: break;
        }
    }

    if (EndDate > wxDate::Today())
    {
        mmErrorDialogs::MessageWarning(this, _("End date is in the future\nQuotes will be updated until today")
            , _("Stock History Error"));
        EndDate = wxDate::Today();
    }

    wxString CSVQuotes;
    wxString URL = mmex::weblink::YahooQuotesHistory;
    URL += m_stock->SYMBOL;
    URL += wxString::Format("&a=%i", StartDate.GetMonth());
    URL += wxString::Format("&b=%i", StartDate.GetDay());
    URL += wxString::Format("&c=%i", StartDate.GetYear());
    URL += wxString::Format("&d=%i", EndDate.GetMonth());
    URL += wxString::Format("&e=%i", EndDate.GetDay());
    URL += wxString::Format("&f=%i", EndDate.GetYear());
    switch (freq)
    {
    case DAILY: URL += "&g=d"; break;
    case WEEKLY: URL += "&g=w"; break;
    case MONTHLY: URL += "&g=m"; break;
        default: break;
    }
    URL += "&ignore=.csv";
    wxLogDebug("Start Date:%s End Date:%s URL:%s", StartDate.FormatISODate(), EndDate.FormatISODate(), URL);

    int err_code = site_content(URL, CSVQuotes);
    if (err_code != wxURL_NOERR)
    {
        if (err_code == -1) CSVQuotes = _("Stock history not found!");
        mmErrorDialogs::MessageError(this, CSVQuotes, _("Stock History Error"));
        return;
    }

    double dPrice;
    wxString dateStr;
    Model_StockHistory::Data *data;

    wxStringTokenizer tkz(CSVQuotes, "\r\n");
    Model_StockHistory::instance().Savepoint();
    while (tkz.HasMoreTokens())
    {
        wxStringTokenizer tkzSingleLine(tkz.GetNextToken(), ",");
        std::vector<wxString> tokens;
        while (tkzSingleLine.HasMoreTokens())
        {
            const wxString& token = tkzSingleLine.GetNextToken();
            tokens.push_back(token);
        }

        if (tokens[0].Contains("-"))
        {
            dateStr = tokens[0];
            tokens[6].ToDouble(&dPrice);

            if (Model_StockHistory::instance().find(
                    Model_StockHistory::SYMBOL(m_stock->SYMBOL),
                    Model_StockHistory::DB_Table_STOCKHISTORY_V1::DATE(dateStr)
                ).size() == 0
                && dPrice > 0)
            {
                data = Model_StockHistory::instance().create();
                data->SYMBOL = m_stock->SYMBOL;
                data->DATE = dateStr;
                data->VALUE = dPrice;
                data->UPDTYPE = Model_StockHistory::ONLINE;
                Model_StockHistory::instance().save(data);
            }
        }
    }
    Model_StockHistory::instance().ReleaseSavepoint();
    showStockHistory();
}
Esempio n. 28
0
void MatroskaWrapper::GetSubtitles(agi::fs::path const& filename, AssFile *target) {
	MkvStdIO input(filename);
	char err[2048];
	agi::scoped_holder<MatroskaFile*, decltype(&mkv_Close)> file(mkv_Open(&input, err, sizeof(err)), mkv_Close);
	if (!file) throw MatroskaException(err);

	// Get info
	unsigned tracks = mkv_GetNumTracks(file);
	std::vector<unsigned> tracksFound;
	std::vector<std::string> tracksNames;

	// Find tracks
	for (auto track : boost::irange(0u, tracks)) {
		auto trackInfo = mkv_GetTrackInfo(file, track);
		if (trackInfo->Type != 0x11 || trackInfo->CompEnabled) continue;

		// Known subtitle format
		std::string CodecID(trackInfo->CodecID);
		if (CodecID == "S_TEXT/SSA" || CodecID == "S_TEXT/ASS" || CodecID == "S_TEXT/UTF8") {
			tracksFound.push_back(track);
			tracksNames.emplace_back(agi::format("%d (%s %s)", track, CodecID, trackInfo->Language));
			if (trackInfo->Name) {
				tracksNames.back() += ": ";
				tracksNames.back() += trackInfo->Name;
			}
		}
	}

	// No tracks found
	if (tracksFound.empty())
		throw MatroskaException("File has no recognised subtitle tracks.");

	unsigned trackToRead;
	// Only one track found
	if (tracksFound.size() == 1)
		trackToRead = tracksFound[0];
	// Pick a track
	else {
		int choice = wxGetSingleChoiceIndex(_("Choose which track to read:"), _("Multiple subtitle tracks found"), to_wx(tracksNames));
		if (choice == -1)
			throw agi::UserCancelException("canceled");

		trackToRead = tracksFound[choice];
	}

	// Picked track
	mkv_SetTrackMask(file, ~(1 << trackToRead));
	auto trackInfo = mkv_GetTrackInfo(file, trackToRead);
	std::string CodecID(trackInfo->CodecID);
	bool srt = CodecID == "S_TEXT/UTF8";
	bool ssa = CodecID == "S_TEXT/SSA";

	AssParser parser(target, !ssa);

	// Read private data if it's ASS/SSA
	if (!srt) {
		// Read raw data
		std::string priv((const char *)trackInfo->CodecPrivate, trackInfo->CodecPrivateSize);

		// Load into file
		boost::char_separator<char> sep("\r\n");
		for (auto const& cur : boost::tokenizer<boost::char_separator<char>>(priv, sep))
			parser.AddLine(cur);
	}
	// Load default if it's SRT
	else {
		target->LoadDefault(false, OPT_GET("Subtitle Format/SRT/Default Style Catalog")->GetString());
		parser.AddLine("[Events]");
	}

	// Read timecode scale
	auto segInfo = mkv_GetFileInfo(file);
	int64_t timecodeScale = mkv_TruncFloat(trackInfo->TimecodeScale) * segInfo->TimecodeScale;

	// Progress bar
	auto totalTime = double(segInfo->Duration) / timecodeScale;
	DialogProgress progress(nullptr, _("Parsing Matroska"), _("Reading subtitles from Matroska file."));
	progress.Run([&](agi::ProgressSink *ps) { read_subtitles(ps, file, &input, srt, totalTime, &parser); });
}
Esempio n. 29
0
//WARNING: event ID must match enum ddDataType!!! this event was created on view
void ddTextTableItemFigure::OnGenericPopupClick(wxCommandEvent &event, hdDrawingView *view)
{
	wxTextEntryDialog *nameDialog = NULL;
	ddPrecisionScaleDialog *numericDialog = NULL;
	wxString tmpString;
	int answer;
	int tmpprecision;
	long tmpvalue;
	hdRemoveDeleteDialog *delremDialog = NULL;

	switch(event.GetId())
	{
		case MNU_DDADDCOLUMN:
			nameDialog = new wxTextEntryDialog(view, wxT("New column name"), wxT("Add a column"));
			answer = nameDialog->ShowModal();
			if (answer == wxID_OK)
			{
				tmpString = nameDialog->GetValue();
				getOwnerColumn()->getOwnerTable()->addColumn(view->getIdx(), new ddColumnFigure(tmpString, getOwnerColumn()->getOwnerTable()));
				view->notifyChanged();
			}
			delete nameDialog;
			break;
		case MNU_DELCOLUMN:
			answer = wxMessageBox(wxT("Are you sure you wish to delete column ") + getText(true) + wxT("?"), wxT("Delete column?"), wxYES_NO | wxNO_DEFAULT, view);
			if (answer == wxYES)
			{
				getOwnerColumn()->getOwnerTable()->removeColumn(view->getIdx(), getOwnerColumn());
				view->notifyChanged();
			}
			break;
		case MNU_AUTONAMCOLUMN:
			getOwnerColumn()->activateGenFkName();
			getOwnerColumn()->getFkSource()->syncAutoFkName();
			view->notifyChanged();
			break;
		case MNU_RENAMECOLUMN:
			nameDialog = new wxTextEntryDialog(view, wxT("New column name"), wxT("Rename Column"), getText());
			nameDialog->ShowModal();
			if(getOwnerColumn()->isGeneratedForeignKey()) //after a manual user column rename, deactivated automatic generation of fk name.
				getOwnerColumn()->deactivateGenFkName();
			setText(nameDialog->GetValue());
			delete nameDialog;
			view->notifyChanged();
			break;
		case MNU_NOTNULL:
			if(getOwnerColumn()->isNotNull())
				getOwnerColumn()->setColumnOption(null);
			else
				getOwnerColumn()->setColumnOption(notnull);
			view->notifyChanged();
			break;
		case MNU_PKEY:
			if(getOwnerColumn()->isPrimaryKey())
			{
				getOwnerColumn()->disablePrimaryKey();
			}
			else
			{
				getOwnerColumn()->enablePrimaryKey();
				getOwnerColumn()->setColumnOption(notnull);
			}
			view->notifyChanged();
			break;
		case MNU_UKEY:
			getOwnerColumn()->toggleColumnKind(uk, view);
			view->notifyChanged();
			break;
		case MNU_TYPESERIAL:
			setDataType(dt_serial);  //Should use setDataType always to set this value to allow fk to work flawlessly
			recalculateDisplayBox();
			getOwnerColumn()->displayBoxUpdate();
			getOwnerColumn()->getOwnerTable()->updateTableSize();
			view->notifyChanged();
			break;
		case MNU_TYPEBOOLEAN:
			setDataType(dt_boolean);
			recalculateDisplayBox();
			getOwnerColumn()->displayBoxUpdate();
			getOwnerColumn()->getOwnerTable()->updateTableSize();
			view->notifyChanged();
			break;
		case MNU_TYPEINTEGER:
			setDataType(dt_integer);
			recalculateDisplayBox();
			getOwnerColumn()->displayBoxUpdate();
			getOwnerColumn()->getOwnerTable()->updateTableSize();
			view->notifyChanged();
			break;
		case MNU_TYPEMONEY:
			setDataType(dt_money);
			recalculateDisplayBox();
			getOwnerColumn()->displayBoxUpdate();
			getOwnerColumn()->getOwnerTable()->updateTableSize();
			view->notifyChanged();
			break;
		case MNU_TYPEVARCHAR:
			setDataType(dt_varchar);
			tmpprecision = wxGetNumberFromUser(_("Varchar size"),
			                                   _("Size for varchar datatype"),
			                                   _("Varchar size"),
			                                   getPrecision(), 0, 255, view);
			if (tmpprecision >= 0)
			{
				setPrecision(tmpprecision);
				setScale(-1);
			}
			recalculateDisplayBox();
			getOwnerColumn()->displayBoxUpdate();
			getOwnerColumn()->getOwnerTable()->updateTableSize();
			view->notifyChanged();
			break;
		case MNU_TYPEOTHER:
			answer = wxGetSingleChoiceIndex(wxT("New column datatype"), wxT("Column Datatypes"), dataTypes(), view);
			if(answer >= 0)
			{
				view->notifyChanged();
				if(answer == dt_varchar || answer == dt_bit || answer == dt_char || answer == dt_interval || answer == dt_varbit)
				{
					tmpprecision = wxGetNumberFromUser(_("datatype size"),
					                                   _("Size for datatype"),
					                                   _("size"),
					                                   getPrecision(), 0, 255, view);
					if (tmpprecision >= 0)
					{
						setPrecision(tmpprecision);
						setScale(-1);
					}
					recalculateDisplayBox();
					getOwnerColumn()->displayBoxUpdate();
					getOwnerColumn()->getOwnerTable()->updateTableSize();
				}
				if(answer == dt_numeric)
				{
					numericDialog = new ddPrecisionScaleDialog(	view,
					        NumToStr((long)getPrecision()),
					        NumToStr((long)getScale()));
					numericDialog->ShowModal();
					numericDialog->GetValue1().ToLong(&tmpvalue);
					setPrecision(tmpvalue);
					numericDialog->GetValue2().ToLong(&tmpvalue);
					setScale(tmpvalue);
					delete numericDialog;
					recalculateDisplayBox();
					getOwnerColumn()->displayBoxUpdate();
					getOwnerColumn()->getOwnerTable()->updateTableSize();
				}


				setDataType( (ddDataType) answer );
				recalculateDisplayBox();
				getOwnerColumn()->displayBoxUpdate();
				getOwnerColumn()->getOwnerTable()->updateTableSize();
			}
			break;
		case MNU_TYPEPKEY_CONSTRAINTNAME:
			tmpString = wxGetTextFromUser(wxT("New name of primary key:"), getOwnerColumn()->getOwnerTable()->getPkConstraintName(), getOwnerColumn()->getOwnerTable()->getPkConstraintName(), view);
			if(tmpString.length() > 0)
			{
				getOwnerColumn()->getOwnerTable()->setPkConstraintName(tmpString);
				view->notifyChanged();
			}
			break;
		case MNU_TYPEUKEY_CONSTRAINTNAME:
			answer = wxGetSingleChoiceIndex(wxT("Select Unique Key constraint to edit name"), wxT("Select Unique Constraint to edit name:"), getOwnerColumn()->getOwnerTable()->getUkConstraintsNames(), view);
			if(answer >= 0)
			{
				tmpString = wxGetTextFromUser(wxT("Change name of Unique Key constraint:"), getOwnerColumn()->getOwnerTable()->getUkConstraintsNames().Item(answer), getOwnerColumn()->getOwnerTable()->getUkConstraintsNames().Item(answer), view);
				if(tmpString.length() > 0)
				{
					getOwnerColumn()->getOwnerTable()->getUkConstraintsNames().Item(answer) = tmpString;
					view->notifyChanged();
				}
			}
			break;
		case MNU_DELTABLE:

			delremDialog = new hdRemoveDeleteDialog(wxT("Are you sure you wish to delete table ") + getOwnerColumn()->getOwnerTable()->getTableName() + wxT("?"), wxT("Delete table?"), view);
			answer = delremDialog->ShowModal();
			ddTableFigure *table = getOwnerColumn()->getOwnerTable();
			if (answer == DD_DELETE)
			{
				ddDrawingEditor *editor = (ddDrawingEditor *) view->editor();
				//Unselect table at all diagrams
				editor->removeFromAllSelections(table);
				//Drop foreign keys with this table as origin or destination
				table->processDeleteAlert(view->getDrawing());
				//Drop table
				editor->deleteModelFigure(table);
				editor->getDesign()->refreshBrowser();
				view->notifyChanged();
			}
			else if(answer == DD_REMOVE)
			{
				ddDrawingEditor *editor = (ddDrawingEditor *) view->editor();
				editor->getExistingDiagram(view->getIdx())->removeFromSelection(table);
				editor->getExistingDiagram(view->getIdx())->remove(table);
				view->notifyChanged();
			}
			delete delremDialog;
			break;
	}
}
Esempio n. 30
0
wxFontEncoding
wxFontMapper::CharsetToEncoding(const wxString& charset, bool interactive)
{
    // try the ways not needing the users intervention first
    int encoding = wxFontMapperBase::NonInteractiveCharsetToEncoding(charset);

    // if we failed to find the encoding, ask the user -- unless disabled
    if ( encoding == wxFONTENCODING_UNKNOWN )
    {
        // this is the special value which disables asking the user (he had
        // chosen to suppress this the last time)
        encoding = wxFONTENCODING_SYSTEM;
    }
#if wxUSE_CHOICEDLG
    else if ( (encoding == wxFONTENCODING_SYSTEM) && interactive )
    {
        // prepare the dialog data

        // the dialog title
        wxString title(m_titleDialog);
        if ( !title )
            title << wxTheApp->GetAppDisplayName() << _(": unknown charset");

        // the message
        wxString msg;
        msg.Printf(_("The charset '%s' is unknown. You may select\nanother charset to replace it with or choose\n[Cancel] if it cannot be replaced"), charset);

        // the list of choices
        const size_t count = GetSupportedEncodingsCount();

        wxString *encodingNamesTranslated = new wxString[count];

        for ( size_t i = 0; i < count; i++ )
        {
            encodingNamesTranslated[i] = GetEncodingDescription(GetEncoding(i));
        }

        // the parent window
        wxWindow *parent = m_windowParent;
        if ( !parent )
            parent = wxTheApp->GetTopWindow();

        // do ask the user and get back the index in encodings table
        int n = wxGetSingleChoiceIndex(msg, title,
                                       count,
                                       encodingNamesTranslated,
                                       parent);

        delete [] encodingNamesTranslated;

        if ( n != -1 )
        {
            encoding = GetEncoding(n);
        }

#if wxUSE_CONFIG && wxUSE_FILECONFIG
        // save the result in the config now
        wxFontMapperPathChanger path(this, FONTMAPPER_CHARSET_PATH);
        if ( path.IsOk() )
        {
            wxConfigBase *config = GetConfig();

            // remember the alt encoding for this charset -- or remember that
            // we don't know it
            long value = n == -1 ? (long)wxFONTENCODING_UNKNOWN : (long)encoding;
            if ( !config->Write(charset, value) )
            {
                wxLogError(_("Failed to remember the encoding for the charset '%s'."), charset);
            }
        }
#endif // wxUSE_CONFIG
    }
#else
    wxUnusedVar(interactive);
#endif // wxUSE_CHOICEDLG

    return (wxFontEncoding)encoding;
}