CString MiscModule_Impl::getDownloadDirByToday()
{
	CString csDownloadDir = getDownloadDir();
	CTime timeDate(time(0));
	CString csTime = timeDate.Format(_T("%Y-%m-%d"));
	
	return csDownloadDir + csTime + _T("\\");
}
void WIZARD_3DSHAPE_LIBS_DOWNLOADER::setupReview()
{
    // Prepare the last page of the wizard.

    m_LocalFolderInfo->SetLabel( getDownloadDir() );

    wxArrayInt checkedIndices;
    m_checkList3Dlibnames->GetCheckedItems( checkedIndices );

    m_libraries.Clear();

    // populate m_libraries with the name of libraries, without the github path:
    for( unsigned int ii = 0; ii < checkedIndices.GetCount(); ++ii )
    {
        m_libraries.Add( m_checkList3Dlibnames->GetString( checkedIndices[ii] ).AfterLast( '/' ) );
    }

    // Adjust number of rows in m_gridLibReview:
    int delta = m_libraries.GetCount() - m_gridLibReview->GetNumberRows();

    if( delta < 0 )
        m_gridLibReview->DeleteRows( -delta );
    else if( delta > 0 )
        m_gridLibReview->AppendRows( delta );

    // For user info, verify the existence of these libs in local folder
    wxArrayString liblist;
    wxFileName fn;
    fn.AssignDir( getDownloadDir() );

    for( unsigned int ii = 0; ii < m_libraries.GetCount(); ++ii )
    {
        fn.SetName( m_libraries[ii] );

        wxDir dirs;
        bool isNew = ! dirs.Exists( fn.GetFullPath() );
        wxString info = isNew ? _( "New" ) : _( "Update" );

        liblist.Add( info + wxT("  ") + m_libraries[ii] );

        m_gridLibReview->SetCellValue( ii, 0, info );
        m_gridLibReview->SetCellValue( ii, 1, m_libraries[ii] );
    }

    m_gridLibReview->AutoSizeColumn( 0 );
}
WIZARD_3DSHAPE_LIBS_DOWNLOADER::~WIZARD_3DSHAPE_LIBS_DOWNLOADER()
{
    // Use this if you want to store kicad lib URL in pcbnew/cvpcb section config:
    // wxConfigBase* cfg = Kiface().KifaceSettings();

    // Use this if you want to store kicad lib URL in common section config:
    wxConfigBase* cfg = Pgm().CommonSettings();
    cfg->Write( KICAD_3DLIBS_URL_KEY, GetGithubURL() );
    cfg->Write( KICAD_3DLIBS_LAST_DOWNLOAD_DIR, getDownloadDir() );
}
void WIZARD_3DSHAPE_LIBS_DOWNLOADER::OnBrowseButtonClick( wxCommandEvent& aEvent )
{
    wxString path = getDownloadDir();

    path = wxDirSelector( _("Choose a folder to save the downloaded libraries" ),
                             path, 0, wxDefaultPosition, this );

    if( !path.IsEmpty() && wxDirExists( path ) )
    {
        setDownloadDir( path );
        updateGithubControls();
    }
}
// Download the .pretty libraries found in aUrlLis and store them on disk
// in a master folder
bool WIZARD_FPLIB_TABLE::downloadGithubLibsFromList( wxArrayString& aUrlList,
        wxString* aErrorMessage )
{
    // Display a progress bar to show the downlaod state
    wxProgressDialog pdlg( _( "Downloading libraries" ), wxEmptyString, aUrlList.GetCount() );

    // Download libs:
    for( unsigned ii = 0; ii < aUrlList.GetCount(); ii++ )
    {
        wxString& libsrc_name = aUrlList[ii];
        wxString libdst_name;

        // Extract the lib name from the full URL:
        wxURI url( libsrc_name );
        wxFileName fn( url.GetPath() );
        // Set our local path
        fn.SetPath( getDownloadDir() );
        libdst_name = fn.GetFullPath();

        if( !wxDirExists( libdst_name ) )
            wxMkdir( libdst_name );

        pdlg.Update( ii, libsrc_name );
        pdlg.Refresh();
        pdlg.Update();

        try
        {
            PLUGIN::RELEASER src( IO_MGR::PluginFind( IO_MGR::GITHUB ) );
            PLUGIN::RELEASER dst( IO_MGR::PluginFind( IO_MGR::KICAD ) );

            wxArrayString footprints = src->FootprintEnumerate( libsrc_name );

            for( unsigned i = 0;  i < footprints.size();  ++i )
            {
                std::auto_ptr<MODULE> m( src->FootprintLoad( libsrc_name, footprints[i] ) );
                dst->FootprintSave( libdst_name, m.get() );
                // m is deleted here by auto_ptr.
            }
        }
        catch( const IO_ERROR& ioe )
        {
            if( aErrorMessage )
                aErrorMessage->Printf( _( "Error:\n'%s'\nwhile downloading library:\n'%s'" ),
                                       GetChars( ioe.errorText ), GetChars( libsrc_name ) );
            return false;
        }
    }

    return true;
}
void WIZARD_FPLIB_TABLE::OnBrowseButtonClick( wxCommandEvent& aEvent )
{
    wxString path = getDownloadDir();

    path = wxDirSelector( _("Choose a folder to save the downloaded libraries" ),
                          path, 0, wxDefaultPosition, this );

    if( !path.IsEmpty() && wxDirExists( path ) )
    {
        setDownloadDir( path );

        wxConfigBase* cfg = Pgm().CommonSettings();
        cfg->Write( KICAD_FPLIBS_LAST_DOWNLOAD_DIR, path );

        updateGithubControls();
    }
}
void WIZARD_FPLIB_TABLE::updateGithubControls()
{
#ifndef BUILD_GITHUB_PLUGIN
    m_radioAddGithub->Enable( false );
#endif

    // Disable inputs that have no meaning for the selected source
    bool githubEnabled = ( GetLibSource() == GITHUB );
    m_textCtrlGithubURL->Enable( githubEnabled );
    m_downloadGithub->Enable( githubEnabled );
    m_downloadDir->Enable( githubEnabled && wantLocalCopy() );
    m_btnBrowse->Enable( githubEnabled && wantLocalCopy() );

    bool valid = !( githubEnabled && wantLocalCopy() ) || wxFileName::IsDirWritable( getDownloadDir() );

    // Do not allow to go further unless there is a valid directory selected
    m_invalidDir->Show( !valid );
    enableNext( valid );
}
void WIZARD_FPLIB_TABLE::OnWizardFinished( wxWizardEvent& aEvent )
{
#ifdef BUILD_GITHUB_PLUGIN
    // Shall we download a localy copy of the libraries
    if( GetLibSource() == GITHUB && m_downloadGithub->GetValue() )
    {
        wxString error;
        wxArrayString libs;

        // Prepare a list of libraries to download
        for( std::vector<LIBRARY>::const_iterator it = m_libraries.begin();
                it != m_libraries.end(); ++it )
        {
            wxASSERT( it->GetPluginType() == IO_MGR::GITHUB );

            if( it->GetStatus() != LIBRARY::INVALID )
                libs.Add( it->GetAbsolutePath() );
        }

        if( !downloadGithubLibsFromList( libs, &error ) )
        {
            DisplayError( this, error );
            m_libraries.clear();
        }
        else
        {
            // Now libraries are stored locally, so update the paths to point to the download folder
            for( std::vector<LIBRARY>::iterator it = m_libraries.begin();
                    it != m_libraries.end(); ++it )
            {
                wxString path = it->GetAbsolutePath();
                path.Replace( GetGithubURL(), getDownloadDir() );
                it->setPath( path );
                it->setPluginType( IO_MGR::KICAD );
            }
        }
    }
#endif
}
void WIZARD_3DSHAPE_LIBS_DOWNLOADER::updateGithubControls()
{
    bool valid = wxFileName::IsDirWritable( getDownloadDir() );

    // Shows or not the warning text if the target 3d folder does not exist, or is not
    // writable.
    m_invalidDirWarningText->Show( !valid );
    m_bitmapDirWarn->Show( !valid );

    // If the dialog starts with m_invalidDirWarningText and m_bitmapDirWarn not shown
    // the size and position of the sizer containing these widgets can be incorrect,
    // until a wxSizeEvent is fired, and the widgets are not shown, or truncated,
    // at least on Windows. So fire a dummy wxSizeEvent if the size looks bad
    if( m_invalidDirWarningText->IsShown() && m_invalidDirWarningText->GetSize().x < 2 )
    {
        wxSizeEvent event( GetSize() );
        wxPostEvent( this, event );
    }

    // Allow to go further only if there is a valid target directory selected
    enableNext( valid );
}
// Download the .pretty libraries folders found in aUrlList and store them on disk
// in a master folder
bool WIZARD_3DSHAPE_LIBS_DOWNLOADER::downloadGithubLibsFromList( wxArrayString& aUrlList,
                                                     wxString* aErrorMessage )
{
    // Display a progress bar to show the download state
    // The title is updated for each downloaded library.
    // the state will be updated by downloadOneLib() for each file.
    wxProgressDialog pdlg( _( "Downloading 3D libraries" ), wxEmptyString,
                           aUrlList.GetCount(), GetParent(),
                           wxPD_CAN_ABORT | wxPD_APP_MODAL | wxPD_AUTO_HIDE );

    wxString url_base = GetGithubURL();

    // Download libs:
    for( unsigned ii = 0; ii < aUrlList.GetCount(); ii++ )
    {
        wxString& libsrc_name = aUrlList[ii];

        // Extract the lib name from the full URL:
        wxString url = GetGithubURL() + wxT( "/" ) + libsrc_name;
        wxFileName fn( libsrc_name );
        // Set our local path
        fn.SetPath( getDownloadDir() );
        wxString libdst_name = fn.GetFullPath();

        // Display the name of the library to download in the wxProgressDialog
        pdlg.SetTitle( wxString::Format( wxT("%s [%d/%d]" ),
                       libsrc_name.AfterLast( '/' ).GetData(),
                       ii + 1, aUrlList.GetCount() ) );

        if( !wxDirExists( libdst_name ) )
            wxMkdir( libdst_name );

        if( !downloadOneLib( url, libdst_name, &pdlg, aErrorMessage ) )
            return false;
    }

    return true;
}