void HeadersDetectorDlg::ProcessFile( ProjectFile* file, wxArrayString& includes )
{
    // We do not care about proper encoding right now.
    // Libraries should never use any native characters in names
    // of their includes and in case of any multibyte encoding
    // multibyte charcters shouldn't hurt us
    // Encoding detector tends to work really slow in some cases

    wxString Ext = file->file.GetExt();
    Ext.MakeLower();

    static const wxChar* Exts[] =
    {
        _T("h"), _T("hxx"), _T("hpp"),
        _T("c"), _T("cpp"), _T("cxx"),
        0
    };

    bool validExt = false;
    for ( const wxChar** ptr = Exts; *ptr; ptr++ )
    {
        if ( Ext == *ptr )
        {
            validExt = true;
            break;
        }
    }
    if ( !validExt )
        return;


    wxFile fl( file->file.GetFullPath() );
    if ( !fl.IsOpened() ) return;
    wxFileOffset contentLength = fl.Length();
    if ( contentLength <= 0 )
        return;

    char* content = new char[contentLength+1];
    char* line = new char[contentLength+1];
    if ( fl.Read(content,contentLength) != contentLength )
    {
        delete[] line;
        delete[] content;
        return;
    }
    content[contentLength] = 0;

    bool blockComment = false;
    for ( size_t pos = 0; pos < static_cast<size_t>(contentLength); )
    {
        // Fetching next line
        char last = 0;
        bool lineEnd = false;
        int lineLength = 0;
        bool lineComment = false;
        bool inStr = false;
        bool inChar = false;
        bool lastCharAdded = false;
        do
        {
            char ch = content[pos++];
            bool thisCharAdded = false;
            switch ( ch )
            {
                case '\n':
                    if ( content[pos] == '\r' )
                        pos++;
                    // Continue to \r
                case '\r':
                    if ( last != '\\' )
                    {
                        lineEnd = true;
                        break;
                    }
                    else if ( lastCharAdded )
                    {
                        // Removing last char since it was '\'
                        // which is removed in the
                        // preprocessor level
                        lineLength--;
                    }
                    break;

                case '*':
                    if ( blockComment )
                    {
                        if ( content[pos] == '/' )
                        {
                            pos++;
                            blockComment = false;
                            break;
                        }
                    }
                    else if ( !lineComment )
                    {
                        thisCharAdded = true;
                        line[lineLength++] = ch;
                    }
                    break;

                case '"':
                    if ( !blockComment && !lineComment )
                    {
                        if ( !inChar )
                        {
                            if ( !inStr )
                                inStr = true;
                            else if ( last != '\\' )
                                inStr = false;
                        }
                        thisCharAdded = true;
                        line[lineLength++] = ch;
                    }
                    break;

                case '\'':
                    if ( !blockComment && !lineComment )
                    {
                        if ( !inStr )
                        {
                            if ( !inChar )
                                inChar = true;
                            else if ( last != '\\' )
                                inChar = false;
                        }
                        thisCharAdded = true;
                        line[lineLength++] = ch;
                    }
                    break;

                case '/':
                    if ( !blockComment && !lineComment && !inStr && !inChar )
                    {
                        if ( content[pos] == '/' )
                        {
                            pos++;
                            lineComment = true;
                            break;
                        }

                        if ( content[pos] == '*' )
                        {
                            pos++;
                            blockComment = true;
                            break;
                        }
                    }

                    // Contnue to default case
                default:
                    if ( !blockComment && !lineComment )
                    {
                        thisCharAdded = true;
                        line[lineLength++] = ch;
                    }
            }
            last = ch;
            lastCharAdded = thisCharAdded;
        }
        while ( !lineEnd && pos < static_cast<size_t>(contentLength) );
        line[lineLength] = 0;

        // Searching for include

        int i=0;
        while ( line[i]==' ' || line[i]=='\t' ) i++;
        if ( line[i++] == '#' )
        {
            while ( line[i]==' ' || line[i]=='\t' ) i++;
            if ( !strncmp( line+i, "include", 7 ) )
            {
                i += 7;
                while ( line[i]==' ' || line[i]=='\t' ) i++;

                wxString include;

                char readTill =
                    ( line[i] == '<' ) ? '>' :
                    ( line[i] == '"' ) ? '"' :
                      0;

                if ( readTill )
                {
                    i++;
                    while ( line[i] && line[i]!=readTill )
                        include += (wxChar)line[i++];
                    if ( line[i] == readTill )
                        includes.Add( include );
                }
            }
        }
    }

    delete[] line;
    delete[] content;
}
bool CFilterConditionsDialog::CreateListControl(int conditions /*=common*/)
{
	wxScrolledWindow* wnd = XRCCTRL(*this, "ID_CONDITIONS", wxScrolledWindow);
	if (!wnd)
		return false;

	m_pListCtrl = new wxCustomHeightListCtrl(this, wxID_ANY, wxDefaultPosition, wnd->GetSize(), wxVSCROLL|wxSUNKEN_BORDER|wxTAB_TRAVERSAL);
	if (!m_pListCtrl)
		return false;
	m_pListCtrl->AllowSelection(false);
	ReplaceControl(wnd, m_pListCtrl);
	CalcMinListWidth();

	if (stringConditionTypes.IsEmpty())
	{
		stringConditionTypes.Add(_("contains"));
		stringConditionTypes.Add(_("is equal to"));
		stringConditionTypes.Add(_("begins with"));
		stringConditionTypes.Add(_("ends with"));
		stringConditionTypes.Add(_("matches regex"));
		stringConditionTypes.Add(_("does not contain"));

		sizeConditionTypes.Add(_("greater than"));
		sizeConditionTypes.Add(_("equals"));
		sizeConditionTypes.Add(_("does not equal"));
		sizeConditionTypes.Add(_("less than"));

		attributeSetTypes.Add(_("is set"));
		attributeSetTypes.Add(_("is unset"));

		attributeConditionTypes.Add(_("Archive"));
		attributeConditionTypes.Add(_("Compressed"));
		attributeConditionTypes.Add(_("Encrypted"));
		attributeConditionTypes.Add(_("Hidden"));
		attributeConditionTypes.Add(_("Read-only"));
		attributeConditionTypes.Add(_("System"));

		permissionConditionTypes.Add(_("owner readable"));
		permissionConditionTypes.Add(_("owner writeable"));
		permissionConditionTypes.Add(_("owner executable"));
		permissionConditionTypes.Add(_("group readable"));
		permissionConditionTypes.Add(_("group writeable"));
		permissionConditionTypes.Add(_("group executable"));
		permissionConditionTypes.Add(_("world readable"));
		permissionConditionTypes.Add(_("world writeable"));
		permissionConditionTypes.Add(_("world executable"));

		dateConditionTypes.Add(_("before"));
		dateConditionTypes.Add(_("equals"));
		dateConditionTypes.Add(_("does not equal"));
		dateConditionTypes.Add(_("after"));
	}

	if (conditions & filter_name)
	{
		filterTypes.Add(_("Filename"));
		filter_type_map.push_back(filter_name);
	}
	if (conditions & filter_size)
	{
		filterTypes.Add(_("Filesize"));
		filter_type_map.push_back(filter_size);
	}
	if (conditions & filter_attributes)
	{
		filterTypes.Add(_("Attribute"));
		filter_type_map.push_back(filter_attributes);
	}
	if (conditions & filter_permissions)
	{
		filterTypes.Add(_("Permission"));
		filter_type_map.push_back(filter_permissions);
	}
	if (conditions & filter_path)
	{
		filterTypes.Add(_("Path"));
		filter_type_map.push_back(filter_path);
	}
	if (conditions & filter_date)
	{
		filterTypes.Add(_("Date"));
		filter_type_map.push_back(filter_date);
	}

	SetFilterCtrlState(true);

	m_pListCtrl->Connect(wxEVT_SIZE, wxSizeEventHandler(CFilterConditionsDialog::OnListSize), 0, this);

	m_pListCtrl->MoveAfterInTabOrder(XRCCTRL(*this, "ID_MATCHTYPE", wxChoice));

	return true;
}
void IncludePathLocator::Locate(wxArrayString& paths, wxArrayString &excludePaths, bool thirdPartyLibs, const wxString &tool) {
	// Common compiler paths - should be placed at top of the include path!
	wxString tmpfile1 = wxFileName::CreateTempFileName(wxT("codelite"));
	wxString command;
	wxString tmpfile = tmpfile1;
	tmpfile += wxT(".cpp");

	wxString bin = tool;
	if(bin.IsEmpty()) {
		bin = wxT("gcc");
	}

	wxRenameFile(tmpfile1, tmpfile);

	// GCC prints parts of its output to stdout and some to stderr
	// redirect all output to stdout
#if defined(__WXMAC__) || defined(__WXGTK__)
	// Mac does not like the standard command
	command = wxString::Format(wxT("%s -v -x c++ /dev/null -fsyntax-only"), bin.c_str());
#else
	command = wxString::Format(wxT("%s -v -x c++ %s -fsyntax-only"), bin.c_str(), tmpfile.c_str());
#endif

	wxString outputStr = wxShellExec(command, wxEmptyString);
	wxRemoveFile( tmpfile );

	wxArrayString outputArr = wxStringTokenize(outputStr, wxT("\n\r"), wxTOKEN_STRTOK);
	// Analyze the output
	bool collect(false);
	for(size_t i=0; i<outputArr.GetCount(); i++) {
		if(outputArr[i].Contains(wxT("#include <...> search starts here:"))) {
			collect = true;
			continue;
		}

		if(outputArr[i].Contains(wxT("End of search list."))) {
			break;
		}

		if(collect) {

			wxString file = outputArr.Item(i).Trim().Trim(false);

			// on Mac, (framework directory) appears also,
			// but it is harmless to use it under all OSs
			file.Replace(wxT("(framework directory)"), wxT(""));
			file.Trim().Trim(false);

			wxFileName includePath(file, wxT(""));
			includePath.Normalize();

			paths.Add( includePath.GetPath() );
		}
	}

	if(thirdPartyLibs) {
		// try to locate QMAKE
		wxFileConfig  qmakeConf(wxEmptyString, wxEmptyString, m_mgr->GetStartupDirectory() + wxT("/config/qmake.ini"));
		wxString      groupName;
		long          index(0);
		wxArrayString out;
		wxString      qmake(wxT("qmake"));

		if (qmakeConf.GetFirstGroup(groupName, index)) {
			// we got qmake configuration, use it instead of the default qmake command
			qmake = qmakeConf.Read(groupName + wxT("/qmake"));
		}

		// Run: qmake -query QT_INSTALL_PREFIX
		wxString cmd;
		cmd << qmake << wxT(" -query QT_INSTALL_PREFIX");

#ifdef __WXGTK__
		cmd << wxT(" 2>/dev/null");
#endif

		out = ExecCommand(cmd);

		if (out.IsEmpty() == false ) {

			wxString qt_output (out.Item(0));
			qt_output.Trim().Trim(false);

#if defined(__WXGTK__)||defined(__WXMAC__)
			wxString pathQt4, pathQt3, pathQt;
			pathQt4 << qt_output << wxFileName::GetPathSeparator() << wxT("include") << wxFileName::GetPathSeparator() << wxT("qt4");
			pathQt3 << qt_output << wxFileName::GetPathSeparator() << wxT("include") << wxFileName::GetPathSeparator() << wxT("qt3");
			pathQt  << qt_output << wxFileName::GetPathSeparator() << wxT("include");

			if (wxDir::Exists( pathQt4 )) {
				wxString tmpPath;

				tmpPath = pathQt4 + wxT("/QtCore");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

				tmpPath = pathQt4 + wxT("/QtGui");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

				tmpPath = pathQt4 + wxT("/QtXml");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

			} else if (wxDir::Exists( pathQt3 ) ) {

				wxString tmpPath;

				tmpPath = pathQt3 + wxT("/QtCore");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

				tmpPath = pathQt3 + wxT("/QtGui");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

				tmpPath = pathQt3 + wxT("/QtXml");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

			} else if (wxDir::Exists( pathQt ) ) {

				wxString tmpPath;

				tmpPath = pathQt + wxT("/QtCore");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );

				tmpPath = pathQt + wxT("/QtGui");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( pathQt );

				tmpPath = pathQt + wxT("/QtXml");
				if(wxFileName::DirExists(tmpPath))
					paths.Add( tmpPath );
			}

#else // __WXMSW__
			wxString pathWin;
			pathWin << qt_output << wxFileName::GetPathSeparator() << wxT("include") << wxFileName::GetPathSeparator();
			if (wxDir::Exists( pathWin )) {

				wxString tmpPath;

				tmpPath = pathWin + wxT("QtCore");
				if(wxFileName::DirExists(tmpPath)) {
					wxFileName fn(tmpPath, wxT(""));
					paths.Add( fn.GetPath() );
				}

				tmpPath = pathWin + wxT("QtGui");
				if(wxFileName::DirExists(tmpPath)) {
					wxFileName fn(tmpPath, wxT(""));
					paths.Add( fn.GetPath() );
				}

				tmpPath = pathWin + wxT("QtXml");
				if(wxFileName::DirExists(tmpPath)) {
					wxFileName fn(tmpPath, wxT(""));
					paths.Add( fn.GetPath() );
				}
			}
#endif
		}

		// Try wxWidgets
#ifdef __WXMSW__
		// On Windows, just read the content of the WXWIN environment variable
		wxString wxwin;
		if (wxGetEnv(wxT("WX_INCL_HOME"), &wxwin)) {
			// we got the path to the installation of wxWidgets
			if (wxDir::Exists(wxwin)) {
				paths.Add( wxwin );
				excludePaths.Add( wxwin + wxT("\\univ") );
				excludePaths.Add( wxwin + wxT("\\unix") );
			}
		}
#else
		// run wx-config and parse the output
		out.Clear();
		out = ExecCommand(wxT("wx-config --cxxflags 2>/dev/null"));
		if (out.IsEmpty() == false) {
			wxString line ( out.Item(0) );
			int where = line.Find(wxT(" -I"));
			while (where != wxNOT_FOUND) {
				line = line.Mid(where + 3);
				paths.Add( line.BeforeFirst(wxT(' ')) );
				where = line.Find(wxT(" -I"));
			}
		}
#endif
	}
}
Example #4
0
void ListCtrlWrapper::GetIncludeFile(wxArrayString& headers) const { headers.Add(wxT("#include <wx/listctrl.h>")); }
    /*! \brief Run the dialogue.
     *
     * \param aItems wxArrayString&
     * \return bool
     *
     */
    bool wxsImageComboEditorDlg::Execute(wxArrayString &aItems)
    {
        int             i,n;
        int             j,k;
        long            ll;
        wxString        ss, tt;
        wxTreeItemId    root;
        wxTreeItemId    item;
        wxTreeItemIdValue   cookie;
        wxBitmap        bmp;
        wxsImageList    *ilist;


        // get name of combo-box and image-list
        n = aItems.GetCount();
        if(n == 0){
            m_ComboName = _("<unknown>");
            m_ImageName = _("<none>");
        }
        else if(n == 1){
            m_ComboName = aItems.Item(0);
            m_ImageName = _("<none>");
        }
        else{
            m_ComboName = aItems.Item(0);
            m_ImageName = aItems.Item(1);
        }

        // show the names
        ss = _("Combo Box: ") + m_ComboName;
        StaticText1->SetLabel(ss);

        ss = _("Image List: ") + m_ImageName;
        StaticText9->SetLabel(ss);

        // a valid image-list given?
        m_ImageList.RemoveAll();
        ilist = (wxsImageList *) wxsImageListEditorDlg::FindTool(NULL, m_ImageName);
        if(ilist == NULL){
            m_pCmbImage->Enable(false);
        }
        else{
            m_pCmbImage->Enable(true);
            ilist->GetImageList(m_ImageList);
        }

        // setup the combo-box image selector
        m_pCmbImage->Clear();
        m_pCmbImage->Append(_("<none>"));

        n = m_ImageList.GetImageCount();
        for(i=0; i<n; i++){
            ss.Printf(_T("%3d"), i);
            bmp = m_ImageList.GetBitmap(i);

            m_pCmbImage->Append(ss, bmp);
        }

        m_pCmbImage->SetSelection(0);

        // clear old junk
        m_pTree->DeleteAllItems();

        // make a root item
        root = m_pTree->AddRoot(_("root"));

        // make sure we are using the image list -- even if it is empty
        m_pTree->SetImageList(&m_ImageList);

        // add all the new items
        n = aItems.GetCount();
        for(i = 2;i < n;i++){
            ss = aItems.Item(i);
            j  = ss.Find(_T(","));
            k = -1;
            if(j != wxNOT_FOUND){
                tt = ss.Left(j);
                ss.erase(0, j + 1);
                if(tt.ToLong(&ll)) k = ll;
            }
            item = m_pTree->AppendItem(root, ss, k);
        }

        // show the dialog and wait for a response
        n = ShowModal();

        // save all new stuff?
        if(n == wxOK){
            // must save combo-box name and image-list name
            aItems.Clear();
            aItems.Add(m_ComboName);
            aItems.Add(m_ImageName);

            // fetch the actual root item, it might have been recreated or
            // even deleted while executing the dialog
            root = m_pTree->GetRootItem();
            if (root.IsOk())
            {
                // save text of all children of the root item
                // these are actually the only things seen by the user
                item = m_pTree->GetFirstChild(root, cookie);
                while(item.IsOk()){
                    ss = m_pTree->GetItemText(item);
                    k  = m_pTree->GetItemImage(item, wxTreeItemIcon_Normal);

                    tt.Printf(_T("%d,"), k);
                    ss = tt + ss;

                    aItems.Add(ss);

                    item = m_pTree->GetNextChild(root, cookie);
                }
            }
        }

        // done
        return (n == wxOK);
    }
bool GITHUB_GETLIBLIST::GetFootprintLibraryList( wxArrayString& aList )
{
    std::string fullURLCommand;
    int page = 1;
    int itemCountMax = 99;              // Do not use a valu > 100, it does not work
    strcpy( m_option_string, "application/json" );

    // Github max items returned is 100 per page

    if( !repoURL2listURL( m_repoURL, &fullURLCommand, itemCountMax, page ) )
    {
        wxString msg = wxString::Format( _( "malformed URL:\n'%s'" ), GetChars( m_repoURL ) );
        wxMessageBox( msg );
        return false;
    }

    // The URL lib names are relative to the server name.
    // so add the server name to them.
    wxURI repo( m_repoURL );
    wxString urlPrefix = repo.GetScheme() + wxT( "://" ) + repo.GetServer() + wxT( "/" );

    wxString errorMsg;
    const char  sep = ',';      // Separator fields, in json returned file
    wxString    tmp;
    int items_count_per_page = 0;
    std::string& json_image = GetBuffer();

    while( 1 )
    {
        bool success = remoteGetJSON( fullURLCommand, &errorMsg );

        if( !success )
        {
            wxMessageBox( errorMsg );
            return false;
        }


        for( unsigned ii = 0; ii < json_image.size(); ii++ )
        {
            if( json_image[ii] == sep || ii == json_image.size() - 1 )
            {
                if( tmp.StartsWith( wxT( "\"full_name\"" ) ) )
                {
                    #define QUOTE '\"'
                    // Remove useless quotes:
                    if( tmp[tmp.Length() - 1] == QUOTE )
                        tmp.RemoveLast();

                    if( tmp.EndsWith( m_libs_ext ) )
                    {
                        aList.Add( tmp.AfterLast( ':' ) );
                        int idx = aList.GetCount() - 1;

                        if( aList[idx][0] == QUOTE )
                            aList[idx].Remove( 0, 1 );

                        aList[idx].Prepend( urlPrefix );
                    }

                    items_count_per_page++;
                }

                tmp.Clear();
            }
            else
                tmp << json_image[ii];
        }

        if( items_count_per_page >= itemCountMax )
        {
            page++;
            repoURL2listURL( m_repoURL, &fullURLCommand, itemCountMax, page );
            items_count_per_page = 0;
            ClearBuffer();
        }
        else
            break;
    }

    aList.Sort();
    return true;
}
Example #7
0
void eSettings::GetRecents(const wxJSONValue& jarray, wxArrayString& recents) const {
	for (int i = 0; i < jarray.Size(); ++i) {
		recents.Add(jarray.ItemAt(i).AsString());
	}
}
Example #8
0
void ChoiceBookWrapper::GetIncludeFile(wxArrayString& headers) const { headers.Add(wxT("#include <wx/choicebk.h>")); }
void wxsEventsEditor::FindFunctions(const wxString& ArgType,wxArrayString& Array)
{
	wxString Code = wxsCoder::Get()->GetCode(m_Header,
        wxsCodeMarks::Beg(m_Language,_T("Handlers"),m_Class),
        wxsCodeMarks::End(m_Language),
        false,false);

    switch ( m_Language )
    {
        case wxsCPP:
        {
            // Basic parsing

            for(;;)
            {
                // Searching for void statement - it may begin new fuunction declaration

                int Pos = Code.Find(_T("void"));
                if ( Pos == -1 ) break;

                // Removing all before function name
                Code.Remove(0,Pos+4).Trim(false);

                // Getting function name
                Pos  = 0;
                while ( (int)Code.Length() > Pos )
                {
                    wxChar First = Code.GetChar(Pos);
                    if ( ( First<_T('A') || First>_T('Z') ) &&
                         ( First<_T('a') || First>_T('z') ) &&
                         ( First<_T('0') || First>_T('9') ) &&
                         ( First!=_T('_') ) )
                    {
                        break;
                    }
                    Pos++;
                }
                wxString NewFunctionName = Code.Mid(0,Pos);
                Code.Remove(0,Pos).Trim(false);
                if ( !Code.Length() ) break;

                // Parsing arguments
                if ( Code.GetChar(0) != _T('(') ) continue;
                Code.Remove(0,1).Trim(false);
                if ( !Code.Length() ) break;

                // Getting argument type
                Pos  = 0;
                while ( (int)Code.Length() > Pos )
                {
                    wxChar First = Code.GetChar(Pos);
                    if ( ( First<_T('A') || First>_T('Z') ) &&
                         ( First<_T('a') || First>_T('z') ) &&
                         ( First<_T('0') || First>_T('9') ) &&
                         ( First!=_T('_') ) )
                    {
                        break;
                    }
                    Pos++;
                }
                wxString NewEventType = Code.Mid(0,Pos);
                Code.Remove(0,Pos).Trim(false);
                if ( !Code.Length() ) break;

                // Checking if the rest of declaratin is valid
                if ( Code.GetChar(0) != _T('&') ) continue;
                Code.Remove(0,1).Trim(false);
                if ( !Code.Length() ) break;

                // Skipping argument name
                Pos  = 0;
                while ( (int)Code.Length() > Pos )
                {
                    wxChar First = Code.GetChar(Pos);
                    if ( ( First<_T('A') || First>_T('Z') ) &&
                         ( First<_T('a') || First>_T('z') ) &&
                         ( First<_T('0') || First>_T('9') ) &&
                         ( First!=_T('_') ) )
                    {
                        break;
                    }
                    Pos++;
                }
                Code.Remove(0,Pos).Trim(false);
                if ( !Code.Length() ) break;

                if ( Code.GetChar(0) != _T(')') ) continue;
                Code.Remove(0,1).Trim(false);
                if ( !Code.Length() ) break;

                if ( Code.GetChar(0) != _T(';') ) continue;
                Code.Remove(0,1).Trim(false);

                if ( NewFunctionName.Length() == 0 || NewEventType.Length() == 0 ) continue;

                // We got new function, checking event type and adding to array

                if ( !ArgType.Length() || ArgType == NewEventType )
                {
                    Array.Add(NewFunctionName);
                }
            }
            break;
        }

        default:
        {
            wxsCodeMarks::Unknown(_T("wxsEventsEditor::FindFunctions"),m_Language);
        }
    }

}
Example #10
0
size_t wxGetAvailableDrives(wxArrayString &paths, wxArrayString &names, wxArrayInt &icon_ids)
{
#ifdef wxHAS_FILESYSTEM_VOLUMES

#ifdef __WXWINCE__
    // No logical drives; return "\"
    paths.Add(wxT("\\"));
    names.Add(wxT("\\"));
    icon_ids.Add(wxFileIconsTable::computer);
#elif defined(__WIN32__) && wxUSE_FSVOLUME
    // TODO: this code (using wxFSVolumeBase) should be used for all platforms
    //       but unfortunately wxFSVolumeBase is not implemented everywhere
    const wxArrayString as = wxFSVolumeBase::GetVolumes();

    for (size_t i = 0; i < as.GetCount(); i++)
    {
        wxString path = as[i];
        wxFSVolume vol(path);
        int imageId;
        switch (vol.GetKind())
        {
            case wxFS_VOL_FLOPPY:
                if ( (path == wxT("a:\\")) || (path == wxT("b:\\")) )
                    imageId = wxFileIconsTable::floppy;
                else
                    imageId = wxFileIconsTable::removeable;
                break;
            case wxFS_VOL_DVDROM:
            case wxFS_VOL_CDROM:
                imageId = wxFileIconsTable::cdrom;
                break;
            case wxFS_VOL_NETWORK:
                if (path[0] == wxT('\\'))
                    continue; // skip "\\computer\folder"
                imageId = wxFileIconsTable::drive;
                break;
            case wxFS_VOL_DISK:
            case wxFS_VOL_OTHER:
            default:
                imageId = wxFileIconsTable::drive;
                break;
        }
        paths.Add(path);
        names.Add(vol.GetDisplayName());
        icon_ids.Add(imageId);
    }
#elif defined(__OS2__)
    APIRET rc;
    ULONG ulDriveNum = 0;
    ULONG ulDriveMap = 0;
    rc = ::DosQueryCurrentDisk(&ulDriveNum, &ulDriveMap);
    if ( rc == 0)
    {
        size_t i = 0;
        while (i < 26)
        {
            if (ulDriveMap & ( 1 << i ))
            {
                const wxString path = wxFileName::GetVolumeString(
                                        'A' + i, wxPATH_GET_SEPARATOR);
                const wxString name = wxFileName::GetVolumeString(
                                        'A' + i, wxPATH_NO_SEPARATOR);

                // Note: If _filesys is unsupported by some compilers,
                //       we can always replace it by DosQueryFSAttach
                char filesysname[20];
#ifdef __WATCOMC__
                ULONG cbBuffer = sizeof(filesysname);
                PFSQBUFFER2 pfsqBuffer = (PFSQBUFFER2)filesysname;
                APIRET rc = ::DosQueryFSAttach(name.fn_str(),0,FSAIL_QUERYNAME,pfsqBuffer,&cbBuffer);
                if (rc != NO_ERROR)
                {
                    filesysname[0] = '\0';
                }
#else
                _filesys(name.fn_str(), filesysname, sizeof(filesysname));
#endif
                /* FAT, LAN, HPFS, CDFS, NFS */
                int imageId;
                if (path == wxT("A:\\") || path == wxT("B:\\"))
                    imageId = wxFileIconsTable::floppy;
                else if (!strcmp(filesysname, "CDFS"))
                    imageId = wxFileIconsTable::cdrom;
                else if (!strcmp(filesysname, "LAN") ||
                         !strcmp(filesysname, "NFS"))
                    imageId = wxFileIconsTable::drive;
                else
                    imageId = wxFileIconsTable::drive;
                paths.Add(path);
                names.Add(name);
                icon_ids.Add(imageId);
            }
            i ++;
        }
    }
#else // !__WIN32__, !__OS2__
    /* If we can switch to the drive, it exists. */
    for ( char drive = 'A'; drive <= 'Z'; drive++ )
    {
        const wxString
            path = wxFileName::GetVolumeString(drive, wxPATH_GET_SEPARATOR);

        if (wxIsDriveAvailable(path))
        {
            paths.Add(path);
            names.Add(wxFileName::GetVolumeString(drive, wxPATH_NO_SEPARATOR));
            icon_ids.Add(drive <= 2 ? wxFileIconsTable::floppy
                                    : wxFileIconsTable::drive);
        }
    }
#endif // __WIN32__/!__WIN32__

#elif defined(__WXMAC__) && wxOSX_USE_COCOA_OR_CARBON

    ItemCount volumeIndex = 1;
    OSErr err = noErr ;

    while( noErr == err )
    {
        HFSUniStr255 volumeName ;
        FSRef fsRef ;
        FSVolumeInfo volumeInfo ;
        err = FSGetVolumeInfo(0, volumeIndex, NULL, kFSVolInfoFlags , &volumeInfo , &volumeName, &fsRef);
        if( noErr == err )
        {
            wxString path = wxMacFSRefToPath( &fsRef ) ;
            wxString name = wxMacHFSUniStrToString( &volumeName ) ;

            if ( (volumeInfo.flags & kFSVolFlagSoftwareLockedMask) || (volumeInfo.flags & kFSVolFlagHardwareLockedMask) )
            {
                icon_ids.Add(wxFileIconsTable::cdrom);
            }
            else
            {
                icon_ids.Add(wxFileIconsTable::drive);
            }
            // todo other removable

            paths.Add(path);
            names.Add(name);
            volumeIndex++ ;
        }
    }

#elif defined(__UNIX__)
    paths.Add(wxT("/"));
    names.Add(wxT("/"));
    icon_ids.Add(wxFileIconsTable::computer);
#else
    #error "Unsupported platform in wxGenericDirCtrl!"
#endif
    wxASSERT_MSG( (paths.GetCount() == names.GetCount()), wxT("The number of paths and their human readable names should be equal in number."));
    wxASSERT_MSG( (paths.GetCount() == icon_ids.GetCount()), wxT("Wrong number of icons for available drives."));
    return paths.GetCount();
}
void DataViewListCtrlWrapper::GetIncludeFile(wxArrayString& headers) const { headers.Add("#include <wx/dataview.h>"); }
Example #12
0
void GLCanvasWrapper::GetIncludeFile(wxArrayString& headers) const { headers.Add("#include <wx/glcanvas.h>"); }
Example #13
0
// ----------------------------------------------------------------------------
// Initialize importer
bool
GStreamerImportFileHandle::Init()
{
   // Create a URI from the filename
   mUri = g_strdup_printf("file:///%s", mFilename.ToUTF8().data());
   if (!mUri)
   {
      wxLogMessage(wxT("GStreamerImport couldn't create URI"));
      return false;
   }

   // Create the stream context array
   mStreams = g_ptr_array_new();
   if (!mStreams)
   {
      wxLogMessage(wxT("GStreamerImport couldn't create context array"));
      return false;
   }

   // Create a pipeline
   mPipeline = gst_pipeline_new("pipeline");

   // Get its bus
   mBus = gst_pipeline_get_bus(GST_PIPELINE(mPipeline));

   // Create uridecodebin and set up signal handlers
   mDec = gst_element_factory_make("uridecodebin", "decoder");
   g_signal_connect(mDec, "autoplug-select", G_CALLBACK(GStreamerAutoplugSelectCallback), (gpointer) this);
   g_signal_connect(mDec, "pad-added", G_CALLBACK(GStreamerPadAddedCallback), (gpointer) this);
   g_signal_connect(mDec, "pad-removed", G_CALLBACK(GStreamerPadRemovedCallback), (gpointer) this);

   // Set the URI
   g_object_set(G_OBJECT(mDec), "uri", mUri, NULL);

   // Add the decoder to the pipeline
   if (!gst_bin_add(GST_BIN(mPipeline), mDec))
   {
      wxMessageBox(wxT("Unable to add decoder to pipeline"),
                   wxT("GStreamer Importer"));

      // Cleanup expected to occur in destructor
      return false;
   }

   // Run the pipeline
   GstStateChangeReturn state = gst_element_set_state(mPipeline, GST_STATE_PAUSED);
   if (state == GST_STATE_CHANGE_FAILURE)
   {
      wxMessageBox(wxT("Unable to set stream state to paused."),
                   wxT("GStreamer Importer"));
      return false;
   }

   // Collect info while the stream is prerolled
   //
   // Unfortunately, for some files this may cause a slight "pause" in the GUI
   // without a progress dialog appearing.  Not much can be done about it other
   // than throwing up an additional progress dialog and displaying two dialogs
   // may be confusing to the users.

   // Process messages until we get an error or the ASYNC_DONE message is received
   bool success;
   while (ProcessBusMessage(success) && success)
   {
      // Give wxWidgets a chance to do housekeeping
      wxSafeYield();
   }

   // Build the stream info array
   g_mutex_lock(&mStreamsLock);
   for (guint i = 0; i < mStreams->len; i++)
   {
      GStreamContext *c = (GStreamContext *) g_ptr_array_index(mStreams, i);

      // Create stream info string
      wxString strinfo;
      strinfo.Printf(wxT("Index[%02d], Type[%s], Channels[%d], Rate[%d]"),
                     (unsigned int) i,
                     wxString::FromUTF8(c->mType).c_str(),
                     (int) c->mNumChannels,
                     (int) c->mSampleRate);
      mStreamInfo.Add(strinfo);
   }
   g_mutex_unlock(&mStreamsLock);

   return success;
}
bool CodeCompletionManager::GetDefinitionsAndSearchPaths(clEditor* editor, wxArrayString& searchPaths,
                                                         wxArrayString& definitions)
{
    // Sanity
    CHECK_PTR_RET_FALSE(editor);

    if(editor->GetProjectName().IsEmpty()) return false;
    if(!clCxxWorkspaceST::Get()->IsOpen()) return false;

    // Support only C/C++ files
    if(!FileExtManager::IsCxxFile(editor->GetFileName().GetFullName())) return false;

    // Get the file's project and get the build configuration settings
    // for it
    ProjectPtr proj = clCxxWorkspaceST::Get()->GetProject(editor->GetProjectName());
    CHECK_PTR_RET_FALSE(proj);

    BuildConfigPtr buildConf = proj->GetBuildConfiguration();
    CHECK_PTR_RET_FALSE(buildConf);

    CompilerPtr compiler = buildConf->GetCompiler();
    CHECK_PTR_RET_FALSE(compiler);

#if 0
    if(buildConf->IsCustomBuild()) {
        definitions = proj->GetPreProcessors();
        CL_DEBUG("CxxPreProcessor will use the following macros:");
        CL_DEBUG_ARR(definitions);
        // Custom builds are handled differently
        CompilationDatabase compileDb;
        compileDb.Open();
        if(compileDb.IsOpened()) {
            // we have compilation database for this workspace
            wxString compileLine, cwd;
            compileDb.CompilationLine(editor->GetFileName().GetFullPath(), compileLine, cwd);

            CL_DEBUG("Pre Processor dimming: %s\n", compileLine);
            CompilerCommandLineParser cclp(compileLine, cwd);
            searchPaths = cclp.GetIncludes();

            // get the mcros
            definitions << cclp.GetMacros();
        }
    }
#endif
    // get the include paths based on the project settings (this is per build configuration)
    searchPaths = proj->GetIncludePaths();
    CL_DEBUG("CxxPreProcessor will use the following include paths:");
    CL_DEBUG_ARR(searchPaths);

    // get the compiler include paths
    // wxArrayString compileIncludePaths = compiler->GetDefaultIncludePaths();

    // includePaths.insert(includePaths.end(), compileIncludePaths.begin(), compileIncludePaths.end());
    definitions = proj->GetPreProcessors();

    // get macros out of workspace
    wxString strWorkspaceMacros = clCxxWorkspaceST::Get()->GetParserMacros();
    wxArrayString workspaceMacros = wxStringTokenize(strWorkspaceMacros, wxT("\n\r"), wxTOKEN_STRTOK);
    for(size_t i = 0; i < workspaceMacros.GetCount(); i++)
        definitions.Add(workspaceMacros.Item(i).Trim().Trim(false).c_str());

    CL_DEBUG("CxxPreProcessor will use the following macros:");
    CL_DEBUG_ARR(definitions);

    // Append the compiler builtin macros
    wxArrayString builtinMacros = compiler->GetBuiltinMacros();
    definitions.insert(definitions.end(), builtinMacros.begin(), builtinMacros.end());

    return true;
}
void ProjectOptionsManipulator::ProcessLinkerLibs(cbProject* prj, const wxString& lib, const wxString& lib_new, wxArrayString& result)
{
  ProjectOptionsManipulatorDlg::EProjectScanOption scan_opt = m_Dlg->GetScanOption();
  switch (scan_opt)
  {
    case ProjectOptionsManipulatorDlg::eSearch:
    case ProjectOptionsManipulatorDlg::eSearchNot:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        bool has_opt = HasOption(prj->GetLinkLibs(), lib);
        if (has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
        {
          result.Add(wxString::Format(_("Project '%s': Contains linker lib '%s'."),
                                      prj->GetTitle().wx_str(), lib.wx_str()));
        }
        else if (!has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
        {
          result.Add(wxString::Format(_("Project '%s': Does not contain linker lib '%s'."),
                                      prj->GetTitle().wx_str(), lib.wx_str()));
        }
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt)
          {
            bool has_opt = HasOption(tgt->GetLinkLibs(), lib);
            if (has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Contains linker lib '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), lib.wx_str()));
            }
            else if (!has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Does not contain linker lib '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), lib.wx_str()));
            }
          }
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eRemove:
    {
      wxString full_lib;
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( HasOption(prj->GetLinkLibs(), lib, full_lib) )
          prj->RemoveLinkLib(full_lib);
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && HasOption(tgt->GetLinkLibs(), lib, full_lib))
            tgt->RemoveLinkLib(lib);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eAdd:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( !HasOption(prj->GetLinkLibs(), lib) )
          prj->AddLinkLib(lib);
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && !HasOption(tgt->GetLinkLibs(), lib))
            tgt->AddLinkLib(lib);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eReplace:
    {
      wxString full_lib;
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( HasOption(prj->GetLinkLibs(), lib, full_lib) )
          prj->ReplaceLinkLib(full_lib, ManipulateOption(full_lib, lib, lib_new));
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && HasOption(tgt->GetLinkLibs(), lib, full_lib))
            tgt->ReplaceLinkLib(full_lib, ManipulateOption(full_lib, lib, lib_new));
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eFiles: // fall-through
    default:
    break;
  }
}
void PluginManager::ReadExtraFilesFromManifestFile(const wxString& pluginFilename,
                                                    wxArrayString& extraFiles)
{
    extraFiles.Clear();

    // find and load plugin's resource file
    // (pluginFilename contains no path info)
    wxFileName fname(pluginFilename);
    fname.SetExt(_T("zip"));
    wxString actual = fname.GetFullName();

    // remove 'lib' prefix from plugin name (if any)
    if (!platform::windows && actual.StartsWith(_T("lib")))
        actual.Remove(0, 3);

    actual = ConfigManager::LocateDataFile(actual, sdPluginsUser | sdDataUser | sdPluginsGlobal | sdDataGlobal);
    if (actual.IsEmpty())
    {
        Manager::Get()->GetLogManager()->LogError(_T("Plugin resource not found: ") + fname.GetFullName());
        return; // not found
    }

    // load XML from ZIP
    wxString contents;
    wxFileSystem* fs = new wxFileSystem;
    wxFSFile* f = fs->OpenFile(actual + _T("#zip:manifest.xml"));
    if (f)
    {
        wxInputStream* is = f->GetStream();
        char tmp[1024] = {};
        while (!is->Eof() && is->CanRead())
        {
            memset(tmp, 0, sizeof(tmp));
            is->Read(tmp, sizeof(tmp) - 1);
            contents << cbC2U((const char*)tmp);
        }
        delete f;
    }
    else
    {
        Manager::Get()->GetLogManager()->LogError(_T("No plugin manifest file in resource: ") + actual);
        delete fs;
        return;
    }
    delete fs;

    // actually load XML document
    TiXmlDocument doc;
    if (!doc.Parse(cbU2C(contents)))
        return;

    TiXmlElement* root = doc.FirstChildElement("CodeBlocks_plugin_manifest_file");
    if (!root)
        return;

    TiXmlElement* extra = root->FirstChildElement("Extra");
    while (extra)
    {
        const char* file = extra->Attribute("file");
        if (file && *file)
        {
            extraFiles.Add(cbC2U(file));
        }

        extra = extra->NextSiblingElement("Extra");
    }
}
Example #17
0
void GetLanguages(wxArrayString &langCodes, wxArrayString &langNames)
{
   wxArrayString tempNames;
   wxArrayString tempCodes;
   LangHash localLanguageName;
   LangHash reverseHash;

   localLanguageName["bg"] = "Balgarski";
   localLanguageName["ca"] = "Catalan";
   localLanguageName["da"] = "Dansk";
   localLanguageName["de"] = "Deutsch";
   localLanguageName["en"] = "English";
   localLanguageName["es"] = "Español";
   localLanguageName["fi"] = "Suomi";
   localLanguageName["fr"] = "Français";
   localLanguageName["it"] = "Italiano";
   localLanguageName["ja"] = "Nihongo";
   localLanguageName["hu"] = "Magyar";
   localLanguageName["mk"] = "Makedonski";
   localLanguageName["nl"] = "Nederlands";
   localLanguageName["nb"] = "Norsk";
   localLanguageName["pl"] = "Polski";
   localLanguageName["pt"] = "Português";
   localLanguageName["ru"] = "Russky";
   localLanguageName["sl"] = "Slovenscina";
   localLanguageName["sv"] = "Svenska";

   wxArrayString audacityPathList = wxGetApp().audacityPathList;
   wxGetApp().AddUniquePathToPathList(wxString::Format("%s/share/locale",
                                                       INSTALL_PREFIX),
                                      audacityPathList);
   wxString lastCode = "";

   int i;
   for(i=wxLANGUAGE_UNKNOWN; i<wxLANGUAGE_USER_DEFINED;i++) {
      const wxLanguageInfo *info = wxLocale::GetLanguageInfo(i);

      if (!info)
         continue;

      wxString fullCode = info->CanonicalName;
      wxString code = fullCode.Left(2);
      wxString name = info->Description;
      bool found = false;

      if (localLanguageName[fullCode] != "") {
         name = localLanguageName[fullCode];
      }
      if (localLanguageName[code] != "") {
         name = localLanguageName[code];
      }

      if (fullCode.Length() < 2)
         continue;

      if (TranslationExists(audacityPathList, fullCode)) {
         tempCodes.Add(fullCode);
         tempNames.Add(name);
         found = true;
      }

      if (code != lastCode) {
         if (TranslationExists(audacityPathList, code)) {
            tempCodes.Add(code);
            tempNames.Add(name);
            found = true;
         }

         if (code == "en" && !found) {
            tempCodes.Add(code);
            tempNames.Add(name);
            found = true;
         }
      }

      lastCode = code;
   }

   // Sort

   unsigned int j;
   for(j=0; j<tempNames.GetCount(); j++)
      reverseHash[tempNames[j]] = tempCodes[j];

   tempNames.Sort();

   for(j=0; j<tempNames.GetCount(); j++) {
      langNames.Add(tempNames[j]);
      langCodes.Add(reverseHash[tempNames[j]]);
   }
}
Example #18
0
void Tokenizer::ReadToEOL(wxArrayString& tokens)
{
    // need to force the tokenizer skip raw expression
    const TokenizerState oldState = m_State;
    m_State = tsReadRawExpression;

    const unsigned int undoIndex = m_TokenIndex;
    const unsigned int undoLine = m_LineNumber;
    SkipToEOL(false);
    const unsigned int lastBufferLen = m_BufferLen - m_TokenIndex;
    m_TokenIndex = undoIndex;
    m_LineNumber = undoLine;

    int level = 0;
    wxArrayString tmp;

    while (m_BufferLen - m_TokenIndex > lastBufferLen)
    {
        while (SkipComment())
            ;
        wxString token = DoGetToken();
        if (token[0] <= _T(' ') || token == _T("\\"))
            continue;

        if (token[0] == _T('('))
            ++level;

        if (level == 0)
        {
            if (tmp.IsEmpty())
            {
                if (!token.Trim().IsEmpty())
                    tokens.Add(token);
            }
            else
            {
                wxString blockStr;
                for (size_t i = 0; i < tmp.GetCount(); ++i)
                    blockStr << tmp[i];
                tokens.Add(blockStr.Trim());
                tmp.Clear();
            }
        }
        else
            tmp.Add(token);

        if (token[0] == _T(')'))
            --level;
    }

    if (!tmp.IsEmpty())
    {
        if (level == 0)
        {
            wxString blockStr;
            for (size_t i = 0; i < tmp.GetCount(); ++i)
                blockStr << tmp[i];
            tokens.Add(blockStr.Trim());
        }
        else
        {
            for (size_t i = 0; i < tmp.GetCount(); ++i)
            {
                if (!tmp[i].Trim().IsEmpty())
                    tokens.Add(tmp[i]);
            }
        }
    }

    m_State = oldState;
}
void AppendArray(const wxArrayString& from, wxArrayString& to)
{
    for (size_t i = 0; i < from.GetCount(); ++i)
        to.Add(from[i]);
}
Example #20
0
bool FFmpegImportFileHandle::InitCodecs()
{
   // Allocate the array of pointers to hold stream contexts pointers
   // Some of the allocated space may be unused (corresponds to video, subtitle, or undecodeable audio streams)
   mScs = (streamContext**)malloc(sizeof(streamContext**)*mFormatContext->nb_streams);
   // Fill the stream contexts
   for (unsigned int i = 0; i < mFormatContext->nb_streams; i++)
   {
      if (mFormatContext->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO)
      {
         //Create a context
         streamContext *sc = new streamContext;
         memset(sc,0,sizeof(*sc));

         sc->m_stream = mFormatContext->streams[i];
         sc->m_codecCtx = sc->m_stream->codec;

         AVCodec *codec = FFmpegLibsInst->avcodec_find_decoder(sc->m_codecCtx->codec_id);
         if (codec == NULL)
         {
            wxLogMessage(wxT("FFmpeg : avcodec_find_decoder() failed. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
            //FFmpeg can't decode this stream, skip it
            delete sc;
            continue;
         }
         if (codec->type != sc->m_codecCtx->codec_type)
         {
            wxLogMessage(wxT("FFmpeg : Codec type mismatch, skipping. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
            //Non-audio codec reported as audio? Nevertheless, we don't need THIS.
            delete sc;
            continue;
         }

         if (FFmpegLibsInst->avcodec_open(sc->m_codecCtx, codec) < 0)
         {
            wxLogMessage(wxT("FFmpeg : avcodec_open() failed. Index[%02d], Codec[%02x - %s]"),i,sc->m_codecCtx->codec_id,sc->m_codecCtx->codec_name);
            //Can't open decoder - skip this stream
            delete sc;
            continue;
         }

         // Stream is decodeable and it is audio. Add it and its decription to the arrays
         wxString strinfo;
         int duration = 0;
         if (sc->m_stream->duration > 0)
           duration = sc->m_stream->duration * sc->m_stream->time_base.num / sc->m_stream->time_base.den;
         else
           duration = mFormatContext->duration / AV_TIME_BASE;
         wxString bitrate = wxT("");
         if (sc->m_codecCtx->bit_rate > 0)
           bitrate.Printf(wxT("%d"),sc->m_codecCtx->bit_rate);
         else
           bitrate.Printf(wxT("?"));
         strinfo.Printf(_("Index[%02x] Codec[%S], Language[%S], Bitrate[%S], Channels[%d], Duration[%d]"),sc->m_stream->id,codec->name,sc->m_stream->language,bitrate.c_str(),sc->m_stream->codec->channels, duration);
         mStreamInfo->Add(strinfo);
         mScs[mNumStreams++] = sc;
      }
      //for video and unknown streams do nothing
   }
   //It doesn't really returns false, but GetStreamCount() will return 0 if file is composed entierly of unreadable streams
   return true;
}
void RibbonButtonBarWrapper::GetIncludeFile(wxArrayString& headers) const
{
    headers.Add("#include <wx/ribbon/buttonbar.h>");
}
Example #22
0
int WXDLLIMPEXP_BASE wxParseCommonDialogsFilter(const wxString& filterStr,
                                           wxArrayString& descriptions,
                                           wxArrayString& filters)
{
    descriptions.Clear();
    filters.Clear();

    wxString str(filterStr);

    wxString description, filter;
    int pos = 0;
    while( pos != wxNOT_FOUND )
    {
        pos = str.Find(wxT('|'));
        if ( pos == wxNOT_FOUND )
        {
            // if there are no '|'s at all in the string just take the entire
            // string as filter and make description empty for later autocompletion
            if ( filters.IsEmpty() )
            {
                descriptions.Add(wxEmptyString);
                filters.Add(filterStr);
            }
            else
            {
                wxFAIL_MSG( wxT("missing '|' in the wildcard string!") );
            }

            break;
        }

        description = str.Left(pos);
        str = str.Mid(pos + 1);
        pos = str.Find(wxT('|'));
        if ( pos == wxNOT_FOUND )
        {
            filter = str;
        }
        else
        {
            filter = str.Left(pos);
            str = str.Mid(pos + 1);
        }

        descriptions.Add(description);
        filters.Add(filter);
    }

#if defined(__WXMOTIF__)
    // split it so there is one wildcard per entry
    for( size_t i = 0 ; i < descriptions.GetCount() ; i++ )
    {
        pos = filters[i].Find(wxT(';'));
        if (pos != wxNOT_FOUND)
        {
            // first split only filters
            descriptions.Insert(descriptions[i],i+1);
            filters.Insert(filters[i].Mid(pos+1),i+1);
            filters[i]=filters[i].Left(pos);

            // autoreplace new filter in description with pattern:
            //     C/C++ Files(*.cpp;*.c;*.h)|*.cpp;*.c;*.h
            // cause split into:
            //     C/C++ Files(*.cpp)|*.cpp
            //     C/C++ Files(*.c;*.h)|*.c;*.h
            // and next iteration cause another split into:
            //     C/C++ Files(*.cpp)|*.cpp
            //     C/C++ Files(*.c)|*.c
            //     C/C++ Files(*.h)|*.h
            for ( size_t k=i;k<i+2;k++ )
            {
                pos = descriptions[k].Find(filters[k]);
                if (pos != wxNOT_FOUND)
                {
                    wxString before = descriptions[k].Left(pos);
                    wxString after = descriptions[k].Mid(pos+filters[k].Len());
                    pos = before.Find(wxT('('),true);
                    if (pos>before.Find(wxT(')'),true))
                    {
                        before = before.Left(pos+1);
                        before << filters[k];
                        pos = after.Find(wxT(')'));
                        int pos1 = after.Find(wxT('('));
                        if (pos != wxNOT_FOUND && (pos<pos1 || pos1==wxNOT_FOUND))
                        {
                            before << after.Mid(pos);
                            descriptions[k] = before;
                        }
                    }
                }
            }
        }
    }
#endif

    // autocompletion
    for( size_t j = 0 ; j < descriptions.GetCount() ; j++ )
    {
        if ( descriptions[j].empty() && !filters[j].empty() )
        {
            descriptions[j].Printf(_("Files (%s)"), filters[j].c_str());
        }
    }

    return filters.GetCount();
}
void ProcessingDlg::SplitPath(const wxString& FileName,wxArrayString& Split)
{
    wxStringTokenizer Tknz(FileName,_T("\\/"));
    while (Tknz.HasMoreTokens()) Split.Add(Tknz.GetNextToken());
}
Example #24
0
void OpenUserDataRec::MakeUserDataRec( const wxString& filter )
{
    if ( !filter.empty() )
    {
        wxString filter2(filter) ;
        int filterIndex = 0;
        bool isName = true ;
        wxString current ;

        for ( unsigned int i = 0; i < filter2.length() ; i++ )
        {
            if ( filter2.GetChar(i) == wxT('|') )
            {
                if ( isName )
                {
                    m_name.Add( current ) ;
                }
                else
                {
                    m_extensions.Add( current ) ;
                    ++filterIndex ;
                }

                isName = !isName ;
                current = wxEmptyString ;
            }
            else
            {
                current += filter2.GetChar(i) ;
            }
        }
        // we allow for compatibility reason to have a single filter expression (like *.*) without
        // an explanatory text, in that case the first part is name and extension at the same time

        wxASSERT_MSG( filterIndex == 0 || !isName , wxT("incorrect format of format string") ) ;
        if ( current.empty() )
            m_extensions.Add( m_name[filterIndex] ) ;
        else
            m_extensions.Add( current ) ;
        if ( filterIndex == 0 || isName )
            m_name.Add( current ) ;

        ++filterIndex ;

        const size_t extCount = m_extensions.GetCount();
        for ( size_t i = 0 ; i < extCount; i++ )
        {
            wxUint32 fileType, creator;
            wxString extension = m_extensions[i];

            // Remove leading '*'
            if ( !extension.empty() && (extension.GetChar(0) == '*') )
                extension = extension.Mid( 1 );

            // Remove leading '.'
            if ( !extension.empty() && (extension.GetChar(0) == '.') )
                extension = extension.Mid( 1 );

            if (wxFileName::MacFindDefaultTypeAndCreator( extension, &fileType, &creator ))
                m_filtermactypes.Add( (OSType)fileType );
            else
                m_filtermactypes.Add( '****' ); // We'll fail safe if it's not recognized
        }
    }
}
void GenericDirCtrlWrapper::GetIncludeFile(wxArrayString& headers) const
{
    headers.Add(wxT("#include <wx/dirctrl.h>"));
}
void ProjectOptionsManipulator::ProcessCustomVars(cbProject* prj, const wxString& var, const wxString& value, wxArrayString& result)
{
  ProjectOptionsManipulatorDlg::EProjectScanOption scan_opt = m_Dlg->GetScanOption();
  switch (scan_opt)
  {
    case ProjectOptionsManipulatorDlg::eSearch:
    case ProjectOptionsManipulatorDlg::eSearchNot:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        bool has_var = prj->HasVar(var);
        if (has_var && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
        {
          result.Add(wxString::Format(_("Project '%s': Does not define custom var '%s'."),
                                      prj->GetTitle().wx_str(), var.wx_str()));
        }
        else if (has_var && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
        {
          result.Add(wxString::Format(_("Project '%s': Defines custom var '%s'."),
                                      prj->GetTitle().wx_str(), var.wx_str()));
        }
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt)
          {
            bool has_var = prj->HasVar(var);
            if (has_var && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Does not define custom var '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), var.wx_str()));
            }
            else if (has_var && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Defines custom var '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), var.wx_str()));
            }
          }
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eRemove:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
        prj->UnsetVar(var);

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt) tgt->UnsetVar(var);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eAdd:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
        prj->SetVar(var, value);

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt) tgt->SetVar(var, value);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eReplace: // fall-through
    case ProjectOptionsManipulatorDlg::eFiles:   // fall-through
    default:
    break;
  }
}
/**
 * Construteur
 * @param origine le répertoire où doit être supprimé les fichiers
 * @param tableau ce tableau est rempli par la classe. Il contient le nom des dossiers vidés. Ces dossiers ne sont pas supprimés
 */
TraverserSupprimeFichier::TraverserSupprimeFichier(wxString origine, wxArrayString &tableau): m_tableau(tableau)
{
    m_origine = origine;
    tableau.Add(m_origine);
}
void ProjectOptionsManipulator::ProcessResCompPaths(cbProject* prj, const wxString& path, const wxString& path_new, wxArrayString& result)
{
  ProjectOptionsManipulatorDlg::EProjectScanOption scan_opt = m_Dlg->GetScanOption();
  switch (scan_opt)
  {
    case ProjectOptionsManipulatorDlg::eSearch:
    case ProjectOptionsManipulatorDlg::eSearchNot:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        bool has_opt = HasOption(prj->GetResourceIncludeDirs(), path);
        if (has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
        {
          result.Add(wxString::Format(_("Project '%s': Contains resource compiler path '%s'."),
                                      prj->GetTitle().wx_str(), path.wx_str()));
        }
        else if (!has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
        {
          result.Add(wxString::Format(_("Project '%s': Does not contain resource compiler path '%s'."),
                                      prj->GetTitle().wx_str(), path.wx_str()));
        }
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt)
          {
            bool has_opt = HasOption(tgt->GetResourceIncludeDirs(), path);
            if (has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearch)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Contains resource compiler path '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), path.wx_str()));
            }
            else if (!has_opt && scan_opt==ProjectOptionsManipulatorDlg::eSearchNot)
            {
              result.Add(wxString::Format(_("Project '%s', target '%s': Does not contain resource compiler path '%s'."),
                                          prj->GetTitle().wx_str(), tgt->GetTitle().wx_str(), path.wx_str()));
            }
          }
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eRemove:
    {
      wxString full_path;
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( HasOption(prj->GetResourceIncludeDirs(), path, full_path) )
          prj->RemoveResourceIncludeDir(full_path);
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && HasOption(tgt->GetResourceIncludeDirs(), path, full_path))
            tgt->RemoveResourceIncludeDir(path);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eAdd:
    {
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( !HasOption(prj->GetResourceIncludeDirs(), path) )
          prj->AddResourceIncludeDir(path);
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && !HasOption(tgt->GetResourceIncludeDirs(), path))
            tgt->AddResourceIncludeDir(path);
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eReplace:
    {
      wxString full_path;
      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eProject) )
      {
        if ( HasOption(prj->GetResourceIncludeDirs(), path, full_path) )
          prj->ReplaceResourceIncludeDir(full_path, ManipulateOption(full_path, path, path_new));
      }

      if ( m_Dlg->GetOptionActive(ProjectOptionsManipulatorDlg::eTarget) )
      {
        for (int i=0; i<prj->GetBuildTargetsCount(); ++i)
        {
          ProjectBuildTarget* tgt = prj->GetBuildTarget(i);
          if (tgt && HasOption(tgt->GetResourceIncludeDirs(), path, full_path))
            tgt->ReplaceResourceIncludeDir(full_path, ManipulateOption(full_path, path, path_new));
        }
      }
    }
    break;

    case ProjectOptionsManipulatorDlg::eFiles: // fall-through
    default:
    break;
  }
}
Example #29
0
void GetLanguages(wxArrayString &langCodes, wxArrayString &langNames)
{
   wxArrayString tempNames;
   wxArrayString tempCodes;
   LangHash localLanguageName;
   LangHash reverseHash;
   LangHash tempHash;

   // MM: Use only ASCII characters here to avoid problems with
   //     charset conversion on Linux platforms
   localLanguageName[wxT("ar")] = wxT("Arabic");
   localLanguageName[wxT("bg")] = wxT("Balgarski");
   localLanguageName[wxT("ca")] = wxT("Catalan");
   localLanguageName[wxT("cs")] = wxT("Czech");
   localLanguageName[wxT("da")] = wxT("Dansk");
   localLanguageName[wxT("de")] = wxT("Deutsch");
   localLanguageName[wxT("el")] = wxT("Ellinika");
   localLanguageName[wxT("en")] = wxT("English");
   localLanguageName[wxT("es")] = wxT("Espanol");
   localLanguageName[wxT("eu")] = wxT("Euskara");
   localLanguageName[wxT("fi")] = wxT("Suomi");
   localLanguageName[wxT("fr")] = wxT("Francais");
   localLanguageName[wxT("ga")] = wxT("Gaeilge");
   localLanguageName[wxT("it")] = wxT("Italiano");
   localLanguageName[wxT("ja")] = wxT("Nihongo");
   localLanguageName[wxT("lt")] = wxT("Lietuviu");
   localLanguageName[wxT("hu")] = wxT("Magyar");
   localLanguageName[wxT("mk")] = wxT("Makedonski");
   localLanguageName[wxT("nl")] = wxT("Nederlands");
   localLanguageName[wxT("nb")] = wxT("Norsk");
   localLanguageName[wxT("pl")] = wxT("Polski");
   localLanguageName[wxT("pt")] = wxT("Portugues");
   localLanguageName[wxT("ru")] = wxT("Russky");
   localLanguageName[wxT("sl")] = wxT("Slovenscina");
   localLanguageName[wxT("sv")] = wxT("Svenska");
   localLanguageName[wxT("uk")] = wxT("Ukrainska");
   localLanguageName[wxT("zh")] = wxT("Chinese (Simplified)");
   localLanguageName[wxT("zh_TW")] = wxT("Chinese (Traditional)");

   wxArrayString audacityPathList = wxGetApp().audacityPathList;
   wxGetApp().AddUniquePathToPathList(wxString::Format(wxT("%s/share/locale"),
                                                       INSTALL_PREFIX),
                                      audacityPathList);
   int i;
   for(i=wxLANGUAGE_UNKNOWN; i<wxLANGUAGE_USER_DEFINED;i++) {
      const wxLanguageInfo *info = wxLocale::GetLanguageInfo(i);

      if (!info)
         continue;

      wxString fullCode = info->CanonicalName;
      wxString code = fullCode.Left(2);
      wxString name = info->Description;

      // Logic: Languages codes are sometimes hierarchical, with a
      // general language code and then a subheading.  For example,
      // zh_TW for Traditional Chinese and zh_CN for Simplified
      // Chinese - but just zh for Chinese in general.  First we look
      // for the full code, like zh_TW.  If that doesn't exist, we
      // look for a code corresponding to the first two letters.
      // Note that if the language for a fullCode exists but we only
      // have a name for the short code, we will use the short code's
      // name but associate it with the full code.  This allows someone
      // to drop in a new language and still get reasonable behavior.

      if (fullCode.Length() < 2)
         continue;

      if (localLanguageName[code] != wxT("")) {
         name = localLanguageName[code];
      }
      if (localLanguageName[fullCode] != wxT("")) {
         name = localLanguageName[fullCode];
      }

      if (TranslationExists(audacityPathList, fullCode)) {
         code = fullCode;
      }

      if (tempHash[code] != wxT(""))
         continue;

      if (TranslationExists(audacityPathList, code) || code==wxT("en")) {
         tempCodes.Add(code);
         tempNames.Add(name);
         tempHash[code] = name;

         /* for debugging
         printf(wxT("code=%s name=%s fullCode=%s name=%s -> %s\n"),
                code.c_str(), localLanguageName[code].c_str(),
                fullCode.c_str(), localLanguageName[fullCode].c_str(),
                name.c_str());
         */
      }
   }

   // Sort

   unsigned int j;
   for(j=0; j<tempNames.GetCount(); j++)
      reverseHash[tempNames[j]] = tempCodes[j];

   tempNames.Sort();

   for(j=0; j<tempNames.GetCount(); j++) {
      langNames.Add(tempNames[j]);
      langCodes.Add(reverseHash[tempNames[j]]);
   }
}
Example #30
0
void SearchThread::GetFiles(const SearchData* data, wxArrayString& files)
{
    wxStringSet_t scannedFiles;

    const wxArrayString& rootDirs = data->GetRootDirs();
    files = data->GetFiles();

    // Populate "scannedFiles" with list of files to scan
    scannedFiles.insert(files.begin(), files.end());

    for(size_t i = 0; i < rootDirs.size(); ++i) {
        // make sure it's really a dir (not a fifo, etc.)
        clFilesScanner scanner;
        std::vector<wxString> filesV;
        if(scanner.Scan(rootDirs.Item(i), filesV, data->GetExtensions())) {
            std::for_each(filesV.begin(), filesV.end(), [&](const wxString& file) { scannedFiles.insert(file); });
        }
    }

    files.clear();
    files.Alloc(scannedFiles.size());
    std::for_each(scannedFiles.begin(), scannedFiles.end(), [&](const wxString& file) { files.Add(file); });

    // Filter all non matching files
    FilterFiles(files, data);
}