/// @brief Opens video
/// @param filename The filename to open
void FFmpegSourceVideoProvider::LoadVideo(wxString filename) {
	wxString FileNameShort = wxFileName(filename).GetShortPath();

	FFMS_Indexer *Indexer = FFMS_CreateIndexer(FileNameShort.utf8_str(), &ErrInfo);
	if (!Indexer)
		throw agi::FileNotFoundError(ErrInfo.Buffer);

	std::map<int,wxString> TrackList = GetTracksOfType(Indexer, FFMS_TYPE_VIDEO);
	if (TrackList.size() <= 0)
		throw VideoNotSupported("no video tracks found");

	// initialize the track number to an invalid value so we can detect later on
	// whether the user actually had to choose a track or not
	int TrackNumber = -1;
	if (TrackList.size() > 1) {
		TrackNumber = AskForTrackSelection(TrackList, FFMS_TYPE_VIDEO);
		// if it's still -1 here, user pressed cancel
		if (TrackNumber == -1)
			throw agi::UserCancelException("video loading cancelled by user");
	}

	// generate a name for the cache file
	wxString CacheName = GetCacheFilename(filename);

	// try to read index
	agi::scoped_holder<FFMS_Index*, void (FFMS_CC*)(FFMS_Index*)>
		Index(FFMS_ReadIndex(CacheName.utf8_str(), &ErrInfo), FFMS_DestroyIndex);

	if (Index && FFMS_IndexBelongsToFile(Index, FileNameShort.utf8_str(), &ErrInfo))
		Index = NULL;

	// time to examine the index and check if the track we want is indexed
	// technically this isn't really needed since all video tracks should always be indexed,
	// but a bit of sanity checking never hurt anyone
	if (Index && TrackNumber >= 0) {
		FFMS_Track *TempTrackData = FFMS_GetTrackFromIndex(Index, TrackNumber);
		if (FFMS_GetNumFrames(TempTrackData) <= 0)
			Index = NULL;
	}

	// moment of truth
	if (!Index) {
		int TrackMask = FFMS_TRACKMASK_NONE;
		if (OPT_GET("Provider/FFmpegSource/Index All Tracks")->GetBool() || OPT_GET("Video/Open Audio")->GetBool())
			TrackMask = FFMS_TRACKMASK_ALL;
		Index = DoIndexing(Indexer, CacheName, TrackMask, GetErrorHandlingMode());
	}
	else {
		FFMS_CancelIndexing(Indexer);
	}

	// update access time of index file so it won't get cleaned away
	wxFileName(CacheName).Touch();

	// we have now read the index and may proceed with cleaning the index cache
	CleanCache();

	// track number still not set?
	if (TrackNumber < 0) {
		// just grab the first track
		TrackNumber = FFMS_GetFirstIndexedTrackOfType(Index, FFMS_TYPE_VIDEO, &ErrInfo);
		if (TrackNumber < 0)
			throw VideoNotSupported(std::string("Couldn't find any video tracks: ") + ErrInfo.Buffer);
	}

	// set thread count
	int Threads = OPT_GET("Provider/Video/FFmpegSource/Decoding Threads")->GetInt();
	if (FFMS_GetVersion() < ((2 << 24) | (17 << 16) | (2 << 8) | 1) && FFMS_GetSourceType(Index) == FFMS_SOURCE_LAVF)
		Threads = 1;

	// set seekmode
	// TODO: give this its own option?
	int SeekMode;
	if (OPT_GET("Provider/Video/FFmpegSource/Unsafe Seeking")->GetBool())
		SeekMode = FFMS_SEEK_UNSAFE;
	else
		SeekMode = FFMS_SEEK_NORMAL;

	VideoSource = FFMS_CreateVideoSource(FileNameShort.utf8_str(), TrackNumber, Index, Threads, SeekMode, &ErrInfo);
	if (!VideoSource)
		throw VideoOpenError(std::string("Failed to open video track: ") + ErrInfo.Buffer);

	// load video properties
	VideoInfo = FFMS_GetVideoProperties(VideoSource);

	const FFMS_Frame *TempFrame = FFMS_GetFrame(VideoSource, 0, &ErrInfo);
	if (!TempFrame)
		throw VideoOpenError(std::string("Failed to decode first frame: ") + ErrInfo.Buffer);

	Width  = TempFrame->EncodedWidth;
	Height = TempFrame->EncodedHeight;
	if (VideoInfo->SARDen > 0 && VideoInfo->SARNum > 0)
		DAR = double(Width) * VideoInfo->SARNum / ((double)Height * VideoInfo->SARDen);
	else
		DAR = double(Width) / Height;

	// Assuming TV for unspecified
	wxString ColorRange = TempFrame->ColorRange == FFMS_CR_JPEG ? "PC" : "TV";

	int CS = TempFrame->ColorSpace;
#if FFMS_VERSION >= ((2 << 24) | (17 << 16) | (1 << 8) | 0)
	if (CS != FFMS_CS_RGB && CS != FFMS_CS_BT470BG && OPT_GET("Video/Force BT.601")->GetBool()) {
		if (FFMS_SetInputFormatV(VideoSource, FFMS_CS_BT470BG, TempFrame->ColorRange, FFMS_GetPixFmt(""), &ErrInfo))
			throw VideoOpenError(std::string("Failed to set input format: ") + ErrInfo.Buffer);

		CS = FFMS_CS_BT470BG;
	}
#endif

	switch (CS) {
		case FFMS_CS_RGB:
			ColorSpace = "None";
			break;
		case FFMS_CS_BT709:
			ColorSpace = wxString::Format("%s.709", ColorRange);
			break;
		case FFMS_CS_UNSPECIFIED:
			ColorSpace = wxString::Format("%s.%s", ColorRange, Width > 1024 || Height >= 600 ? "709" : "601");
			break;
		case FFMS_CS_FCC:
			ColorSpace = wxString::Format("%s.FCC", ColorRange);
			break;
		case FFMS_CS_BT470BG:
		case FFMS_CS_SMPTE170M:
			ColorSpace = wxString::Format("%s.601", ColorRange);
			break;
		case FFMS_CS_SMPTE240M:
			ColorSpace = wxString::Format("%s.240M", ColorRange);
			break;
		default:
			throw VideoOpenError("Unknown video color space");
			break;
	}

	const int TargetFormat[] = { FFMS_GetPixFmt("bgra"), -1 };
	if (FFMS_SetOutputFormatV2(VideoSource, TargetFormat, Width, Height, FFMS_RESIZER_BICUBIC, &ErrInfo)) {
		throw VideoOpenError(std::string("Failed to set output format: ") + ErrInfo.Buffer);
	}

	// get frame info data
	FFMS_Track *FrameData = FFMS_GetTrackFromVideo(VideoSource);
	if (FrameData == NULL)
		throw VideoOpenError("failed to get frame data");
	const FFMS_TrackTimeBase *TimeBase = FFMS_GetTimeBase(FrameData);
	if (TimeBase == NULL)
		throw VideoOpenError("failed to get track time base");

	const FFMS_FrameInfo *CurFrameData;

	// build list of keyframes and timecodes
	std::vector<int> TimecodesVector;
	for (int CurFrameNum = 0; CurFrameNum < VideoInfo->NumFrames; CurFrameNum++) {
		CurFrameData = FFMS_GetFrameInfo(FrameData, CurFrameNum);
		if (CurFrameData == NULL) {
			throw VideoOpenError(STD_STR(wxString::Format("Couldn't get info about frame %d", CurFrameNum)));
		}

		// keyframe?
		if (CurFrameData->KeyFrame)
			KeyFramesList.push_back(CurFrameNum);

		// calculate timestamp and add to timecodes vector
		int Timestamp = (int)((CurFrameData->PTS * TimeBase->Num) / TimeBase->Den);
		TimecodesVector.push_back(Timestamp);
	}
	if (TimecodesVector.size() < 2)
		Timecodes = 25.0;
	else
		Timecodes = agi::vfr::Framerate(TimecodesVector);

	FrameNumber = 0;
}
예제 #2
0
파일: stdpaths.cpp 프로젝트: gitrider/wxsj2
wxString wxStandardPaths::GetPluginsDir() const
{
    return wxFileName(wxGetFullModuleName()).GetPath();
}
예제 #3
0
String pathGetFileName(const String& path)
{
    return wxFileName(path).GetFullName();
}
예제 #4
0
void VideoContext::SetVideo(const wxString &filename) {
	Reset();
	if (filename.empty()) {
		VideoOpen();
		return;
	}

	bool commit_subs = false;
	try {
		provider.reset(new ThreadedFrameSource(filename, this));
		videoProvider = provider->GetVideoProvider();
		videoFile = filename;

		// Check that the script resolution matches the video resolution
		int sx = context->ass->GetScriptInfoAsInt("PlayResX");
		int sy = context->ass->GetScriptInfoAsInt("PlayResY");
		int vx = GetWidth();
		int vy = GetHeight();

		// If the script resolution hasn't been set at all just force it to the
		// video resolution
		if (sx == 0 && sy == 0) {
			context->ass->SetScriptInfo("PlayResX", wxString::Format("%d", vx));
			context->ass->SetScriptInfo("PlayResY", wxString::Format("%d", vy));
			commit_subs = true;
		}
		// If it has been set to something other than a multiple of the video
		// resolution, ask the user if they want it to be fixed
		else if (sx % vx != 0 || sy % vy != 0) {
			switch (OPT_GET("Video/Check Script Res")->GetInt()) {
			case 1: // Ask to change on mismatch
				if (wxYES != wxMessageBox(
					wxString::Format(_("The resolution of the loaded video and the resolution specified for the subtitles don't match.\n\nVideo resolution:\t%d x %d\nScript resolution:\t%d x %d\n\nChange subtitles resolution to match video?"), vx, vy, sx, sy),
					_("Resolution mismatch"),
					wxYES_NO | wxCENTER,
					context->parent))

					break;
				// Fallthrough to case 2
			case 2: // Always change script res
				context->ass->SetScriptInfo("PlayResX", wxString::Format("%d", vx));
				context->ass->SetScriptInfo("PlayResY", wxString::Format("%d", vy));
				commit_subs = true;
				break;
			default: // Never change
				break;
			}
		}

		keyFrames = videoProvider->GetKeyFrames();

		// Set frame rate
		videoFPS = videoProvider->GetFPS();
		if (ovrFPS.IsLoaded()) {
			int ovr = wxMessageBox(_("You already have timecodes loaded. Would you like to replace them with timecodes from the video file?"), _("Replace timecodes?"), wxYES_NO | wxICON_QUESTION);
			if (ovr == wxYES) {
				ovrFPS = agi::vfr::Framerate();
				ovrTimecodeFile.clear();
			}
		}

		// Set aspect ratio
		double dar = videoProvider->GetDAR();
		if (dar > 0)
			SetAspectRatio(4, dar);

		// Set filename
		config::mru->Add("Video", STD_STR(filename));
		StandardPaths::SetPathValue("?video", wxFileName(filename).GetPath());

		// Show warning
		wxString warning = videoProvider->GetWarning();
		if (!warning.empty()) wxMessageBox(warning, "Warning", wxICON_WARNING | wxOK);

		hasSubtitles = false;
		if (filename.Right(4).Lower() == ".mkv") {
			hasSubtitles = MatroskaWrapper::HasSubtitles(filename);
		}

		provider->LoadSubtitles(context->ass);
		VideoOpen();
		KeyframesOpen(keyFrames);
		TimecodesOpen(FPS());
	}
	catch (agi::UserCancelException const&) { }
	catch (agi::FileNotAccessibleError const& err) {
		config::mru->Remove("Video", STD_STR(filename));
		wxMessageBox(lagi_wxString(err.GetMessage()), "Error setting video", wxOK | wxICON_ERROR | wxCENTER);
	}
	catch (VideoProviderError const& err) {
		wxMessageBox(lagi_wxString(err.GetMessage()), "Error setting video", wxOK | wxICON_ERROR | wxCENTER);
	}

	if (commit_subs)
		context->ass->Commit(_("change script resolution"), AssFile::COMMIT_SCRIPTINFO);
	else
		JumpToFrame(0);
}
예제 #5
0
int ExportFFmpeg::Export(AudacityProject *project,
                       int channels, wxString fName,
                       bool selectionOnly, double t0, double t1, MixerSpec *mixerSpec, Tags *metadata, int subformat)
{
   if (!CheckFFmpegPresence())
      return false;
   mChannels = channels;
   // subformat index may not correspond directly to fmts[] index, convert it
   mSubFormat = AdjustFormatIndex(subformat);
   if (channels > ExportFFmpegOptions::fmts[mSubFormat].maxchannels)
   {
      wxMessageBox(
         wxString::Format(
               _("Attempted to export %d channels, but maximum number of channels for selected output format is %d"),
               channels,
               ExportFFmpegOptions::fmts[mSubFormat].maxchannels),
            _("Error"));
      return false;
   }
   mName = fName;
   TrackList *tracks = project->GetTracks();
   bool ret = true;

   if (mSubFormat >= FMT_LAST) return false;

   wxString shortname(ExportFFmpegOptions::fmts[mSubFormat].shortname);
   if (mSubFormat == FMT_OTHER)
      shortname = gPrefs->Read(wxT("/FileFormats/FFmpegFormat"),wxT("matroska"));
   ret = Init(shortname.mb_str(),project, metadata, subformat);

   if (!ret) return false;

   int pcmBufferSize = 1024;
   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(selectionOnly, &numWaveTracks, &waveTracks);
   Mixer *mixer = CreateMixer(numWaveTracks, waveTracks,
      tracks->GetTimeTrack(),
      t0, t1,
      channels, pcmBufferSize, true,
      mSampleRate, int16Sample, true, mixerSpec);
   delete [] waveTracks;

   ProgressDialog *progress = new ProgressDialog(wxFileName(fName).GetName(),
      selectionOnly ?
      wxString::Format(_("Exporting selected audio as %s"), ExportFFmpegOptions::fmts[mSubFormat].description) :
   wxString::Format(_("Exporting entire file as %s"), ExportFFmpegOptions::fmts[mSubFormat].description));

   int updateResult = eProgressSuccess;

   while(updateResult == eProgressSuccess) {
      sampleCount pcmNumSamples = mixer->Process(pcmBufferSize);

      if (pcmNumSamples == 0)
         break;

      short *pcmBuffer = (short *)mixer->GetBuffer();

      EncodeAudioFrame(pcmBuffer,(pcmNumSamples)*sizeof(int16_t)*mChannels);

      updateResult = progress->Update(mixer->MixGetCurrentTime()-t0, t1-t0);
   }

   delete progress;

   delete mixer;

   Finalize();

   return updateResult;
}
예제 #6
0
bool PWUpdaterApp::OnInit()
{
    /* init locale */
    wxStandardPaths &stdPaths = wxStandardPaths::Get();
    wxString localePath = wxFileName(stdPaths.GetExecutablePath()).GetPath(true) + wxT("locale");
    if (!_locale.Init(DetectInstalledLanguages()))
    {
        wxLogWarning(wxT("Selected language is not supported by system."));
    }
    _locale.AddCatalogLookupPathPrefix(localePath);
    _locale.AddCatalog(GetAppName());
    _locale.AddCatalog(wxT("wxstd"));

    /* add description after locale initialization, so that description can be translated. */
    AddLanguageDescriptions();

    /* collect network adapter info */
    if (DetectNetAdapter())
    {
        if (m_adapterList.empty())
        {
            wxLogError(_("No network adapter is availabled, force to use external tftp server!"));
            m_pOpt->SetOption(wxT("UseInternalTftp"), false);
        }
    }
    else
    {
        wxLogError(_("Failed to detect network adapters info, application will be terminated!"));
        return false;
    }

    /*
       use default (the first) active interface when
       (1) database is new created, or
       (2) interface store in database doesn't exist now
     */
    bool useDefaultInterface = false;
    wxString ifName = m_pOpt->GetOption(wxT("ActivedInterface"));
    if (ifName.IsEmpty())
        useDefaultInterface = true;
    else
    {
        wxVector<NetAdapter>::iterator it;
        for (it = m_adapterList.begin(); it != m_adapterList.end(); ++it)
        {
            if (ifName == it->GetName())
                break;
        }

        if (it == m_adapterList.end())
            useDefaultInterface = true;
    }
    if (useDefaultInterface && (m_adapterList.size() > 0))
        m_pOpt->SetOption(wxT("ActivedInterface"), m_adapterList.at(0).GetName());

    /*
       use current working path when
       (1) path stored in database doesn't exist now any more
     */
    bool useCurrentPath = false;
    wxString rootPath = m_pOpt->GetOption(wxT("TftpdRoot"));
    if (!rootPath.empty())
    {
        if (!wxFileName::DirExists(rootPath))
            useCurrentPath = true;
    }
    if (useCurrentPath)
        m_pOpt->SetOption(wxT("TftpdRoot"), wxString(wxEmptyString));

    /* create main frame */
    PWUpdaterFrame *frame = new PWUpdaterFrame(NULL, myID_FRAME);
    frame->Show();
    return true;
}
예제 #7
0
bool Panel_Remaps::DoChangeImgBase( bool b_quiet, bool standalone)
{
	paletteCtrl->Reset(false);
	if( curr_remap == NULL )
		return false;

	int i_EnableEditingTheRemap = 1;
	bool res = false;

	wxString ob_basePath = txtctrl_imgBase->GetValue();
	wxString _basePath = GetObFile( ob_basePath ).GetFullPath();

	//******************************
	// Make the change to the ob_object
	if( mode8bit )
	{
		wxString old_path = curr_remap->GetToken( 0 );
		if( old_path != ob_basePath )
		{
			entity->SetChanged();
			curr_remap->SetToken( 0, ob_basePath );
		}
	}
	else
	{
		ob_object *pal_obobj = entity->GetProperty( wxT("palette") );

		// No current palette tag in the current entity
		wxString old_path = wxString();
		if( pal_obobj == NULL )
		{
			pal_obobj = new ob_object();
			pal_obobj->SetName( wxT("palette") );

			//Try to insert one before the first alternatepal
			size_t nb_remap;
			ob_object** _t = entity->GetSubObjectS( wxT("alternatepal"),nb_remap );
			
			if( _t != NULL )
			{
				_t[nb_remap-1]->InsertObject_After( pal_obobj );
				delete[] _t;
			}
			// Try to insert it before the first anim
			else
				entity->AddProperty( pal_obobj );
		}
		else
			old_path = pal_obobj->GetToken( 0 );

		// Set the palette tag
		if( old_path != ob_basePath )
		{
			// Check if the user really want to change the image base for all remaps
			int res = wxMessageBox( wxT("Do your really want to change the image base for all 16Bits remaps ?"), wxT("Question"), wxYES_NO | wxICON_INFORMATION, this );
			if( res != wxYES )
				return false;

			entity->SetChanged();
			pal_obobj->SetToken( 0, ob_basePath );
		}
	}


	//******************************
	// Check if it's a valid path
	if( ! wxFileName( _basePath ).FileExists() && !b_quiet )
	{
		wxMessageBox( wxT("The Base image for this remap doesn't exist")
		, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );
	}

	else if( IsFileEmpty(_basePath) && !b_quiet )
	{
		wxMessageBox( wxT("The Base image for this remap is an empty file !!")
		, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );
	}


	//******************************
	// Try to load the palette
	else if( paletteCtrl->TryToInitWithImage( _basePath ) )
	{
		res = true;
		i_EnableEditingTheRemap = 0;

		//******************************
		// Try to quietly to load the dest palette
		if( standalone  )
			DoChangeImgDest( true, false);
	}

	EnableEditingTheRemap(i_EnableEditingTheRemap);
	if( standalone )
		Refresh();

	return res;
}
XNODE* NETLIST_EXPORTER_GENERIC::makeDesignHeader()
{
    SCH_SCREEN* screen;
    XNODE*     xdesign = node( wxT("design") );
    XNODE*     xtitleBlock;
    XNODE*     xsheet;
    XNODE*     xcomment;
    wxString   sheetTxt;
    wxFileName sourceFileName;

    // the root sheet is a special sheet, call it source
    xdesign->AddChild( node( wxT( "source" ), g_RootSheet->GetScreen()->GetFileName() ) );

    xdesign->AddChild( node( wxT( "date" ), DateAndTime() ) );

    // which Eeschema tool
    xdesign->AddChild( node( wxT( "tool" ), wxT( "Eeschema " ) + GetBuildVersion() ) );

    /*
        Export the sheets information
    */
    SCH_SHEET_LIST sheetList;

    for( SCH_SHEET_PATH* sheet = sheetList.GetFirst();  sheet;  sheet = sheetList.GetNext() )
    {
        screen = sheet->LastScreen();

        xdesign->AddChild( xsheet = node( wxT( "sheet" ) ) );

        // get the string representation of the sheet index number.
        // Note that sheet->GetIndex() is zero index base and we need to increment the number by one to make
        // human readable
        sheetTxt.Printf( wxT( "%d" ), ( sheetList.GetIndex() + 1 ) );
        xsheet->AddAttribute( wxT( "number" ), sheetTxt );
        xsheet->AddAttribute( wxT( "name" ), sheet->PathHumanReadable() );
        xsheet->AddAttribute( wxT( "tstamps" ), sheet->Path() );


        TITLE_BLOCK tb = screen->GetTitleBlock();

        xsheet->AddChild( xtitleBlock = node( wxT( "title_block" ) ) );

        xtitleBlock->AddChild( node( wxT( "title" ), tb.GetTitle() ) );
        xtitleBlock->AddChild( node( wxT( "company" ), tb.GetCompany() ) );
        xtitleBlock->AddChild( node( wxT( "rev" ), tb.GetRevision() ) );
        xtitleBlock->AddChild( node( wxT( "date" ), tb.GetDate() ) );

        // We are going to remove the fileName directories.
        sourceFileName = wxFileName( screen->GetFileName() );
        xtitleBlock->AddChild( node( wxT( "source" ), sourceFileName.GetFullName() ) );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("1") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment1() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("2") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment2() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("3") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment3() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("4") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment4() );
    }

    return xdesign;
}
void ShellExtensions::OnRunTarget(wxCommandEvent& event)
{
    int ID=event.GetId();
    wxString commandstr;
    wxString consolename;
    wxString workingdir;
    bool windowed=false;
    bool console=false;
    if(ID>=ID_ContextMenu_0&&ID<=ID_ContextMenu_49)
    {
        m_interpnum=m_contextvec[ID-ID_ContextMenu_0];
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
    } else
    if(ID>=ID_SubMenu_0&&ID<=ID_SubMenu_49)
    {
        m_interpnum=ID-ID_SubMenu_0;
        commandstr=m_ic.interps[m_interpnum].command;
        consolename=m_ic.interps[m_interpnum].name;
        windowed=(m_ic.interps[m_interpnum].mode==_("W"));
        console=(m_ic.interps[m_interpnum].mode==_("C"));
        workingdir=m_ic.interps[m_interpnum].wdir;
        m_wildcard=m_ic.interps[m_interpnum].wildcards;
        if(m_ic.interps[m_interpnum].command.Find(_T("$file"))>0 ||
            m_ic.interps[m_interpnum].command.Find(_T("$path"))>0)
        {
            OnSetTarget(event);
            if(!wxFileName::FileExists(m_RunTarget))
            {
                LogMessage(_("ShellExtensions: ")+m_RunTarget+_(" not found"));
                return;
            }
        }
        if(m_ic.interps[m_interpnum].command.Find(_T("$dir"))>0)
        {
            OnSetDirTarget(event);
            if(!wxFileName::DirExists(m_RunTarget))
            {
                LogMessage(_("Shell Extensions: ")+m_RunTarget+_(" not found"));
                return;
            }
            if(m_RunTarget==_T(""))
                return;
        }
        if(m_ic.interps[m_interpnum].command.Find(_T("$mpaths"))>0)
        {
            OnSetMultiTarget(event);
            if(m_RunTarget==_T(""))
                return;
        }
    }
    else
    {
        LogMessage(wxString::Format(_T("WARNING: Unprocessed ShellCommand Menu Message: ID %i, IDbase %i, IDend %i, num items on menu %i"),ID,ID_ContextMenu_0,ID_ContextMenu_49,(int)m_contextvec.size()));
        return;
    }

    m_RunTarget.Replace(_T("*"),_T(" "));

    bool setdir=true;
    commandstr.Replace(_T("$file"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$relfile"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_T("$fname"),wxFileName(m_RunTarget).GetName());
    commandstr.Replace(_T("$fext"),wxFileName(m_RunTarget).GetExt());
    commandstr.Replace(_T("$dir"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$reldir"),wxFileName(m_RunTarget).GetFullName());
    commandstr.Replace(_T("$path"),wxFileName(m_RunTarget).GetShortPath());
    commandstr.Replace(_T("$relpath"),wxFileName(m_RunTarget).GetFullPath());
    if(commandstr.Replace(_T("$mpaths"),m_RunTarget)>0)
        setdir=false;

    // substitute user prompted values in the format: $inputstr{Enter your message}
    int promptind=commandstr.Find(_T("$inputstr{"));
    wxString substitution;
    while(promptind>=0)
    {
        int promptend=commandstr.Mid(promptind+10).Find(_T("}"));
        if(promptend<=0)
        {
            cbMessageBox(_T("Malformed $inputstr in command line -- no closing '}' found: ")+commandstr);
            return;
        }
        else
            promptend++;
        wxTextEntryDialog ted(NULL,commandstr.Mid(promptind+10,promptend-1),consolename,_T(""),wxOK|wxCANCEL);
        if(ted.ShowModal()==wxID_OK)
            substitution=ted.GetValue();
        else
            return;
        commandstr=commandstr.Left(promptind)+substitution+commandstr.Mid(promptind+10+promptend);
        int nextind=commandstr.Mid(promptind+substitution.Len()).Find(_T("$inputstr"));
        if(nextind>=0)
            promptind+=nextind+substitution.Len();
        else
            promptind=-1;
    }

    commandstr.Replace(_T("$interpreter"),wxFileName(m_ic.interps[m_interpnum].command).GetShortPath());
    workingdir.Replace(_T("$parentdir"),wxFileName(m_RunTarget).GetPath());
    if(wxFileName::DirExists(m_RunTarget))
        workingdir.Replace(_T("$dir"),wxFileName(m_RunTarget).GetFullPath());

    if(Manager::Get()->GetMacrosManager())
    {
        Manager::Get()->GetMacrosManager()->RecalcVars(0, 0, 0); // hack to force-update macros
        Manager::Get()->GetMacrosManager()->ReplaceMacros(commandstr);
        Manager::Get()->GetMacrosManager()->ReplaceMacros(workingdir);
    }
    wxString olddir=wxGetCwd();
    if(setdir && workingdir!=_T(""))
    {
        if(!wxSetWorkingDirectory(workingdir))
        {
            LogMessage(_T("Shell Extensions Plugin: Can't change to working directory to ")+workingdir);
            return;
        }
    }

    LogMessage(wxString::Format(_("Launching '%s': %s (in %s)"), consolename.c_str(), commandstr.c_str(), workingdir.c_str()));

    if(windowed)
    {
        wxArrayString astr;
        m_shellmgr->LaunchProcess(commandstr,consolename,_T("Piped Process Control"),astr);
        ShowConsole();
    } else if (console)
    {
        wxString cmdline;
#ifndef __WXMSW__
        // for non-win platforms, use m_ConsoleTerm to run the console app
        wxString term = Manager::Get()->GetConfigManager(_T("app"))->Read(_T("/console_terminal"), DEFAULT_CONSOLE_TERM);
        term.Replace(_T("$TITLE"), _T("'") + consolename + _T("'"));
        cmdline<< term << _T(" ");
        #define CONSOLE_RUNNER "cb_console_runner"
#else
        #define CONSOLE_RUNNER "cb_console_runner.exe"
#endif
        wxString baseDir = ConfigManager::GetExecutableFolder();
        if (wxFileExists(baseDir + wxT("/" CONSOLE_RUNNER)))
            cmdline << baseDir << wxT("/" CONSOLE_RUNNER " ");
        cmdline<<commandstr;

        if(!wxExecute(cmdline))
            cbMessageBox(_T("Command Launch Failed: ")+commandstr);
    } else
    {
        if(!wxExecute(commandstr))
            cbMessageBox(_T("Command Launch Failed: ")+commandstr);
    }
    wxSetWorkingDirectory(olddir);
}
예제 #10
0
wxString wxCmdLineParser::GetUsageString() const
{
    wxString appname;
    if ( m_data->m_arguments.empty() )
    {
        if ( wxTheApp )
            appname = wxTheApp->GetAppName();
    }
    else // use argv[0]
    {
        appname = wxFileName(m_data->m_arguments[0]).GetName();
    }

    // we construct the brief cmd line desc on the fly, but not the detailed
    // help message below because we want to align the options descriptions
    // and for this we must first know the longest one of them
    wxString usage;
    wxArrayString namesOptions, descOptions;

    if ( !m_data->m_logo.empty() )
    {
        usage << m_data->m_logo << wxT('\n');
    }

    usage << wxString::Format(_("Usage: %s"), appname.c_str());

    // the switch char is usually '-' but this can be changed with
    // SetSwitchChars() and then the first one of possible chars is used
    wxChar chSwitch = !m_data->m_switchChars ? wxT('-')
                                             : m_data->m_switchChars[0u];

    bool areLongOptionsEnabled = AreLongOptionsEnabled();
    size_t n, count = m_data->m_options.GetCount();
    for ( n = 0; n < count; n++ )
    {
        wxCmdLineOption& opt = m_data->m_options[n];
        wxString option;

        if ( opt.kind != wxCMD_LINE_USAGE_TEXT )
        {
            usage << wxT(' ');
            if ( !(opt.flags & wxCMD_LINE_OPTION_MANDATORY) )
            {
                usage << wxT('[');
            }

            if ( !opt.shortName.empty() )
            {
                usage << chSwitch << opt.shortName;
            }
            else if ( areLongOptionsEnabled && !opt.longName.empty() )
            {
                usage << wxT("--") << opt.longName;
            }
            else
            {
                if (!opt.longName.empty())
                {
                    wxFAIL_MSG( wxT("option with only a long name while long ")
                                wxT("options are disabled") );
                }
                else
                {
                    wxFAIL_MSG( wxT("option without neither short nor long name") );
                }
            }

            if ( !opt.shortName.empty() )
            {
                option << wxT("  ") << chSwitch << opt.shortName;
            }

            if ( areLongOptionsEnabled && !opt.longName.empty() )
            {
                option << (option.empty() ? wxT("  ") : wxT(", "))
                       << wxT("--") << opt.longName;
            }

            if ( opt.kind != wxCMD_LINE_SWITCH )
            {
                wxString val;
                val << wxT('<') << GetTypeName(opt.type) << wxT('>');
                usage << wxT(' ') << val;
                option << (!opt.longName ? wxT(':') : wxT('=')) << val;
            }

            if ( !(opt.flags & wxCMD_LINE_OPTION_MANDATORY) )
            {
                usage << wxT(']');
            }
        }

        namesOptions.push_back(option);
        descOptions.push_back(opt.description);
    }

    count = m_data->m_paramDesc.GetCount();
    for ( n = 0; n < count; n++ )
    {
        wxCmdLineParam& param = m_data->m_paramDesc[n];

        usage << wxT(' ');
        if ( param.flags & wxCMD_LINE_PARAM_OPTIONAL )
        {
            usage << wxT('[');
        }

        usage << param.description;

        if ( param.flags & wxCMD_LINE_PARAM_MULTIPLE )
        {
            usage << wxT("...");
        }

        if ( param.flags & wxCMD_LINE_PARAM_OPTIONAL )
        {
            usage << wxT(']');
        }
    }

    usage << wxT('\n');

    // set to number of our own options, not counting the standard ones
    count = namesOptions.size();

    // get option names & descriptions for standard options, if any:
    wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
    wxString stdDesc;
    if ( traits )
        stdDesc = traits->GetStandardCmdLineOptions(namesOptions, descOptions);

    // now construct the detailed help message
    size_t len, lenMax = 0;
    for ( n = 0; n < namesOptions.size(); n++ )
    {
        len = namesOptions[n].length();
        if ( len > lenMax )
            lenMax = len;
    }

    for ( n = 0; n < namesOptions.size(); n++ )
    {
        if ( n == count )
            usage << wxT('\n') << stdDesc;

        len = namesOptions[n].length();
        // desc contains text if name is empty
        if (len == 0)
        {
            usage << descOptions[n] << wxT('\n');
        }
        else
        {
            usage << namesOptions[n]
                  << wxString(wxT(' '), lenMax - len) << wxT('\t')
                  << descOptions[n]
                  << wxT('\n');
        }
    }

    return usage;
}
예제 #11
0
bool EDA_APP::ReCreatePrjConfig( const wxString& fileName,
                                 const wxString& GroupName,
                                 bool            ForceUseLocalConfig )
{
    wxFileName fn = fileName;
    wxString defaultFileName;

    // Free old config file.
    if( m_projectSettings )
    {
        delete m_projectSettings;
        m_projectSettings = NULL;
    }

    /* Check the file name does not a KiCad project extension.
     * This allows the user to enter a filename without extension
     * or use an existing name to create te project file
     */
    if( fn.GetExt() != ProjectFileExtension )
    {
        fn.SetExt( ProjectFileExtension );
    }

    /* Update the library search path list if a new project file is loaded. */
    if( m_projectFileName != fn )
    {
        RemoveLibraryPath( m_projectFileName.GetPath() );
        InsertLibraryPath( fn.GetPath(), 0 );
        m_projectFileName = fn;
    }

    // Init local config filename
    if( ForceUseLocalConfig || fn.FileExists() )
    {
        m_projectSettings = new wxFileConfig( wxEmptyString, wxEmptyString,
                                              fn.GetFullPath(), wxEmptyString );
        m_projectSettings->DontCreateOnDemand();

        if( ForceUseLocalConfig )
            return true;

        /* Check the application version against the version saved in the
         * project file.
         *
         * TODO: Push the version test up the stack so that when one of the
         *       KiCad application version changes, the other applications
         *       settings do not get updated.  Practically, this can go away.
         *       It isn't used anywhere as far as I know (WLS).
         */
        int version = -1;
        int def_version = 0;

        m_projectSettings->SetPath( GroupName );
        version = m_projectSettings->Read( wxT( "version" ), def_version );
        m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR );

        if( version > 0 )
        {
            return true;
        }
        else
        {
            delete m_projectSettings;    // Version incorrect
        }
    }

    defaultFileName = m_libSearchPaths.FindValidPath( wxT( "kicad.pro" ) );

    if( !defaultFileName )
    {
        wxLogDebug( wxT( "Template file <kicad.pro> not found." ) );
        fn = wxFileName( GetTraits()->GetStandardPaths().GetDocumentsDir(),
                         wxT( "kicad" ), ProjectFileExtension );
    }
    else
    {
        fn = defaultFileName;
    }

    // Create new project file using the default name.
    m_projectSettings = new wxFileConfig( wxEmptyString, wxEmptyString,
                                          wxEmptyString, fn.GetFullPath() );
    m_projectSettings->DontCreateOnDemand();

    return false;
}
 EventGenerator(const wxFileName& path) : m_base(path)
 {
     m_old = wxFileName();
     m_file = RandomName();
     m_new = RandomName();
 }
예제 #13
0
void OnOptions2(int event_id)
{//==========================
	wxString string;
	int value;

	switch(event_id)
	{
	case MENU_OPT_SPEED:
		value = wxGetNumberFromUser(_T(""),_T(""),_T("Speed"),option_speed,80,500);
		if(value > 0)
		{
			option_speed = value;
			SetParameter(espeakRATE,option_speed,0);
			SetSpeed(3);
		}
		break;

	case MENU_OPT_PUNCT:
		transldlg->t_source->SetValue(_T("<tts:style field=\"punctuation\" mode=\"all\">\n"));
		transldlg->t_source->SetInsertionPointEnd();
		notebook->SetSelection(1);
		break;

	case MENU_OPT_SPELL:
		transldlg->t_source->SetValue(_T("<say-as interpret-as=\"characters\">\n"));
		transldlg->t_source->SetInsertionPointEnd();
		notebook->SetSelection(1);
		break;

	case MENU_OPT_SPELL2:
		transldlg->t_source->SetValue(_T("<say-as interpret-as=\"tts:char\">\n"));
		transldlg->t_source->SetInsertionPointEnd();
		notebook->SetSelection(1);
		break;

	case MENU_PATH_DATA:
		string = wxDirSelector(_T("espeak_data directory"), wxEmptyString);
		if(!string.IsEmpty())
		{
			if(!wxDirExists(string+_T("/voices")))
			{
				wxLogError(_T("No 'voices' directory in ") + string);
				break;
			}
			path_espeakdata = string;
			wxLogMessage(_T("Quit and restart espeakedit to use the new espeak_data location"));
		}
		break;

	case MENU_PATH0:
		string = wxFileSelector(_T("Master phonemes file"),wxFileName(path_phfile).GetPath(),
			_T("phonemes"),_T(""),_T("*"),wxOPEN);
		if(!string.IsEmpty())
		{
			path_phfile = string;
		}
		break;

	case MENU_PATH1:
		string = wxDirSelector(_T("Phoneme source directory"),path_phsource);
		if(!string.IsEmpty())
		{
			path_phsource = string;
		}
		break;

	case MENU_PATH2:
		string = wxDirSelector(_T("Dictionary source directory"),path_dictsource);
		if(!string.IsEmpty())
		{
			path_dictsource = string;
		}
		break;

	case MENU_PATH3:
		string = wxFileSelector(_T("Sound output file"),wxFileName(path_speech).GetPath(),
			_T(""),_T("WAV"),_T("*"),wxSAVE);
		if(!string.IsEmpty())
		{
			path_speech = string;
		}
		break;

	case MENU_PATH4:
		string = wxFileSelector(_T("Voice file to modify formant peaks"),wxFileName(path_speech).GetPath(),
			_T(""),_T(""),_T("*"),wxOPEN);
		if(!string.IsEmpty())
		{
			path_modifiervoice = string;
		}
		break;
	}

	ConfigSetPaths();
}
예제 #14
0
// static 
void ModuleManager::Initialize(CommandHandler &cmdHandler)
{
   wxArrayString audacityPathList = wxGetApp().audacityPathList;
   wxArrayString pathList;
   wxArrayString files;
   wxString pathVar;
   size_t i;

   // Code from LoadLadspa that might be useful in load modules.
   pathVar = wxGetenv(wxT("AUDACITY_MODULES_PATH"));
   if (pathVar != wxT(""))
      wxGetApp().AddMultiPathsToPathList(pathVar, pathList);

   for (i = 0; i < audacityPathList.GetCount(); i++) {
      wxString prefix = audacityPathList[i] + wxFILE_SEP_PATH;
      wxGetApp().AddUniquePathToPathList(prefix + wxT("modules"),
                                         pathList);
   }

   #if defined(__WXMSW__)
   wxGetApp().FindFilesInPathList(wxT("*.dll"), pathList, files);
   #else
   wxGetApp().FindFilesInPathList(wxT("*.so"), pathList, files);
   #endif

   wxString saveOldCWD = ::wxGetCwd();
   for (i = 0; i < files.GetCount(); i++) {
      // As a courtesy to some modules that might be bridges to
      // open other modules, we set the current working
      // directory to be the module's directory.
      wxString prefix = ::wxPathOnly(files[i]);
      ::wxSetWorkingDirectory(prefix);

#ifdef EXPERIMENTAL_MODULE_PREFS
      int iModuleStatus = ModulePrefs::GetModuleStatus( files[i] );
      if( iModuleStatus == kModuleDisabled )
         continue;
      if( iModuleStatus == kModuleFailed )
         continue;
      // New module?  You have to go and explicitly enable it.
      if( iModuleStatus == kModuleNew ){
         // To ensure it is noted in config file and so
         // appears on modules page.
         ModulePrefs::SetModuleStatus( files[i], kModuleNew);
         continue;
      }

      if( iModuleStatus == kModuleAsk )
#endif
      // JKC: I don't like prompting for the plug-ins individually
      // I think it would be better to show the module prefs page,
      // and let the user decide for each one.
      {
         wxString ShortName = wxFileName( files[i] ).GetName();
         wxString msg;
         msg.Printf(_("Module \"%s\" found."), ShortName);
         msg += _("\n\nOnly use modules from trusted sources");
         const wxChar *buttons[] = {_("Yes"), _("No"), NULL};  // could add a button here for 'yes and remember that', and put it into the cfg file.  Needs more thought.
         int action;
         action = ShowMultiDialog(msg, _("Audacity Module Loader"), buttons, _("Try and load this module?"), false);
#ifdef EXPERIMENTAL_MODULE_PREFS
         // If we're not prompting always, accept the answer permanantly
         if( iModuleStatus == kModuleNew ){
            iModuleStatus = (action==1)?kModuleDisabled : kModuleEnabled;
            ModulePrefs::SetModuleStatus( files[i], iModuleStatus );
         }
#endif
         if(action == 1){   // "No"
            continue;
         }
      }
#ifdef EXPERIMENTAL_MODULE_PREFS
      // Before attempting to load, we set the state to bad.
      // That way, if we crash, we won't try again.
      ModulePrefs::SetModuleStatus( files[i], kModuleFailed );
#endif

      auto umodule = make_movable<Module>(files[i]);
      if (umodule->Load())   // it will get rejected if there  are version problems
      {
         auto module = umodule.get();
         Get().mModules.push_back(std::move(umodule));
         // We've loaded and initialised OK.
         // So look for special case functions:
         wxLogNull logNo; // Don't show wxWidgets errors if we can't do these. (Was: Fix bug 544.)
         // (a) for scripting.
         if( scriptFn == NULL )
            scriptFn = (tpRegScriptServerFunc)(module->GetSymbol(wxT(scriptFnName)));
         // (b) for hijacking the entire Audacity panel.
         if( pPanelHijack==NULL )
         {
            pPanelHijack = (tPanelFn)(module->GetSymbol(wxT(mainPanelFnName)));
         }
#ifdef EXPERIMENTAL_MODULE_PREFS
         // Loaded successfully, restore the status.
         ModulePrefs::SetModuleStatus( files[i], iModuleStatus);
#endif
      }
   }
   ::wxSetWorkingDirectory(saveOldCWD);

   // After loading all the modules, we may have a registered scripting function.
   if(scriptFn)
   {
      ScriptCommandRelay::SetCommandHandler(cmdHandler);
      ScriptCommandRelay::SetRegScriptServerFunc(scriptFn);
      NonGuiThread::StartChild(&ScriptCommandRelay::Run);
   }
}
예제 #15
0
int ExportOGG::Export(AudacityProject *project,
                       int numChannels,
                       wxString fName,
                       bool selectionOnly,
                       double t0,
                       double t1,
                       MixerSpec *mixerSpec,
                       Tags *metadata,
                       int WXUNUSED(subformat))
{
   double    rate    = project->GetRate();
   TrackList *tracks = project->GetTracks();
   double    quality = (gPrefs->Read(wxT("/FileFormats/OggExportQuality"), 50)/(float)100.0);

   wxLogNull logNo;            // temporarily disable wxWidgets error messages
   int updateResult = eProgressSuccess;
   int       eos = 0;

   FileIO outFile(fName, FileIO::Output);

   if (!outFile.IsOpened()) {
      wxMessageBox(_("Unable to open target file for writing"));
      return false;
   }

   // All the Ogg and Vorbis encoding data
   ogg_stream_state stream;
   ogg_page         page;
   ogg_packet       packet;

   vorbis_info      info;
   vorbis_comment   comment;
   vorbis_dsp_state dsp;
   vorbis_block     block;

   // Encoding setup
   vorbis_info_init(&info);
   vorbis_encode_init_vbr(&info, numChannels, int(rate + 0.5), quality);

   // Retrieve tags
   if (!FillComment(project, &comment, metadata)) {
      return false;
   }

   // Set up analysis state and auxiliary encoding storage
   vorbis_analysis_init(&dsp, &info);
   vorbis_block_init(&dsp, &block);

   // Set up packet->stream encoder.  According to encoder example,
   // a random serial number makes it more likely that you can make
   // chained streams with concatenation.
   srand(time(NULL));
   ogg_stream_init(&stream, rand());

   // First we need to write the required headers:
   //    1. The Ogg bitstream header, which contains codec setup params
   //    2. The Vorbis comment header
   //    3. The bitstream codebook.
   //
   // After we create those our responsibility is complete, libvorbis will
   // take care of any other ogg bistream constraints (again, according
   // to the example encoder source)
   ogg_packet bitstream_header;
   ogg_packet comment_header;
   ogg_packet codebook_header;

   vorbis_analysis_headerout(&dsp, &comment, &bitstream_header, &comment_header,
         &codebook_header);

   // Place these headers into the stream
   ogg_stream_packetin(&stream, &bitstream_header);
   ogg_stream_packetin(&stream, &comment_header);
   ogg_stream_packetin(&stream, &codebook_header);

   // Flushing these headers now guarentees that audio data will
   // start on a NEW page, which apparently makes streaming easier
   while (ogg_stream_flush(&stream, &page)) {
      outFile.Write(page.header, page.header_len);
      outFile.Write(page.body, page.body_len);
   }

   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(selectionOnly, &numWaveTracks, &waveTracks);
   Mixer *mixer = CreateMixer(numWaveTracks, waveTracks,
                            tracks->GetTimeTrack(),
                            t0, t1,
                            numChannels, SAMPLES_PER_RUN, false,
                            rate, floatSample, true, mixerSpec);
   delete [] waveTracks;

   ProgressDialog *progress = new ProgressDialog(wxFileName(fName).GetName(),
      selectionOnly ?
      _("Exporting the selected audio as Ogg Vorbis") :
      _("Exporting the entire project as Ogg Vorbis"));

   while (updateResult == eProgressSuccess && !eos) {
      float **vorbis_buffer = vorbis_analysis_buffer(&dsp, SAMPLES_PER_RUN);
      sampleCount samplesThisRun = mixer->Process(SAMPLES_PER_RUN);

      if (samplesThisRun == 0) {
         // Tell the library that we wrote 0 bytes - signalling the end.
         vorbis_analysis_wrote(&dsp, 0);
      }
      else {

         for (int i = 0; i < numChannels; i++) {
            float *temp = (float *)mixer->GetBuffer(i);
            memcpy(vorbis_buffer[i], temp, sizeof(float)*SAMPLES_PER_RUN);
         }

         // tell the encoder how many samples we have
         vorbis_analysis_wrote(&dsp, samplesThisRun);
      }

      // I don't understand what this call does, so here is the comment
      // from the example, verbatim:
      //
      //    vorbis does some data preanalysis, then divvies up blocks
      //    for more involved (potentially parallel) processing. Get
      //    a single block for encoding now
      while (vorbis_analysis_blockout(&dsp, &block) == 1) {

         // analysis, assume we want to use bitrate management
         vorbis_analysis(&block, NULL);
         vorbis_bitrate_addblock(&block);

         while (vorbis_bitrate_flushpacket(&dsp, &packet)) {

            // add the packet to the bitstream
            ogg_stream_packetin(&stream, &packet);

            // From vorbis-tools-1.0/oggenc/encode.c:
            //   If we've gone over a page boundary, we can do actual output,
            //   so do so (for however many pages are available).

            while (!eos) {
               int result = ogg_stream_pageout(&stream, &page);
               if (!result) {
                  break;
               }

               outFile.Write(page.header, page.header_len);
               outFile.Write(page.body, page.body_len);

               if (ogg_page_eos(&page)) {
                  eos = 1;
               }
            }
         }
      }

      updateResult = progress->Update(mixer->MixGetCurrentTime()-t0, t1-t0);
   }

   delete progress;;

   delete mixer;

   ogg_stream_clear(&stream);

   vorbis_block_clear(&block);
   vorbis_dsp_clear(&dsp);
   vorbis_info_clear(&info);
   vorbis_comment_clear(&comment);

   outFile.Close();

   return updateResult;
}
void ShellExtensions::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data)
{
	//Some library module is ready to display a pop-up menu.
	//Check the parameter \"type\" and see which module it is
	//and append any items you need in the menu...
	//TIP: for consistency, add a separator as the first item...
	m_contextvec.Empty();
	if(type==mtProjectManager)
	{
	    if(data)
	    {
            if(data->GetKind()==FileTreeData::ftdkProject)
            {
                cbProject* prj = data->GetProject();
                wxString filename=wxFileName(prj->GetFilename()).GetPath();
                wxString name=_T("");
                size_t sep_pos=menu->GetMenuItemCount();
                size_t added=0;
                for(unsigned int i=0;i<m_ic.interps.size();i++)
                    if(WildCardListMatch(m_ic.interps[i].wildcards,name))
                    {
                        m_RunTarget=filename;
                        if(m_ic.interps[i].command.Find(_T("$dir"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$reldir"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$path"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$relpath"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                        {
                            wxString menutext=m_ic.interps[i].name;
                            m_contextvec.Add(i);
                            AddModuleMenuEntry(menu,i,added);
                            added++;
                        }
                    }
                    menu->Append( ID_ProjectOpenInFileBrowser, _T("Open Project Folder in File Browser"), _("Opens the folder containing the project file in the file browser"));
                if(added>0)
                    menu->InsertSeparator(sep_pos);
            }
            if(data->GetKind()==FileTreeData::ftdkFile)
            {
                ProjectFile *f=data->GetProjectFile();
                if(f)
                {
                    wxString filename=f->file.GetFullPath();
                    wxString name=f->file.GetFullName();
                    size_t sep_pos=menu->GetMenuItemCount();
                    size_t added=0;
                    for(unsigned int i=0;i<m_ic.interps.size();i++)
                        if(WildCardListMatch(m_ic.interps[i].wildcards,name))
                        {
                            m_RunTarget=filename;
                            if(m_ic.interps[i].command.Find(_T("$file"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$relfile"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$fname"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$fext"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$path"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$relpath"))>=0 ||
                                m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                            {
                                wxString menutext=m_ic.interps[i].name;
                                m_contextvec.Add(i);
                                AddModuleMenuEntry(menu,i,added);
                                added++;
                            }
                        }
                    if(added>0)
                        menu->InsertSeparator(sep_pos);
                }
            }
	    }
	}
	if(type==mtEditorManager) // also type==mtOpenFilesList - not sure how to find out which file has been right clicked.
	{
        EditorManager* edMan = Manager::Get()->GetEditorManager();
        wxFileName activefile(edMan->GetActiveEditor()->GetFilename());
        wxString filename=activefile.GetFullPath();
        wxString name=activefile.GetFullName();
        size_t sep_pos=menu->GetMenuItemCount();
        size_t added=0;
        for(unsigned int i=0;i<m_ic.interps.size();i++)
            if(WildCardListMatch(m_ic.interps[i].wildcards,name))
            {
                m_RunTarget=filename;
                    if(m_ic.interps[i].command.Find(_T("$file"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$relfile"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$fname"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$fext"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$path"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$relpath"))>=0 ||
                        m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                    {
                        wxString menutext=m_ic.interps[i].name;
                        m_contextvec.Add(i);
                        AddModuleMenuEntry(menu,i,added);
                        added++;
                    }
            }
        if(added>0)
            menu->InsertSeparator(sep_pos);
	}
    if(type==mtUnknown) //Assuming file explorer -- fileexplorer fills the filetreedata with ftdkFile or ftdkFolder as "kind", the folder is the full path of the entry
	    if(data)
	    {
            size_t sep_pos=menu->GetMenuItemCount();
            size_t added=0;
            if(data->GetKind()==FileTreeData::ftdkFile)  //right clicked on folder in file explorer
            {
                wxFileName f(data->GetFolder());
                wxString filename=f.GetFullPath();
                wxString name=f.GetFullName();
                for(unsigned int i=0;i<m_ic.interps.size();i++)
                    if(WildCardListMatch(m_ic.interps[i].wildcards,name))
                    {
                        m_RunTarget=filename;
                        if(m_ic.interps[i].command.Find(_T("$file"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$relfile"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$fname"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$fext"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$path"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$relpath"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                        {
                            wxString menutext=m_ic.interps[i].name;
                            m_contextvec.Add(i);
                            AddModuleMenuEntry(menu,i,added);
                            added++;
                        }
                    }
            }
            if(data->GetKind()==FileTreeData::ftdkFolder) //right clicked on folder in file explorer
            {
                wxFileName f(data->GetFolder());
                wxString filename=f.GetFullPath();
                wxString name=f.GetFullName();
                for(unsigned int i=0;i<m_ic.interps.size();i++)
                    if(WildCardListMatch(m_ic.interps[i].wildcards,name))
                    {
                        m_RunTarget=filename;
                        if(m_ic.interps[i].command.Find(_T("$dir"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$reldir"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$path"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$relpath"))>=0 ||
                            m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                        {
                            wxString menutext=m_ic.interps[i].name;
                            m_contextvec.Add(i);
                            AddModuleMenuEntry(menu,i,added);
                            added++;
                        }
                    }
            }
            if(data->GetKind()==FileTreeData::ftdkVirtualGroup) //right clicked on multiple selections in file explorer
            {
                wxString paths=data->GetFolder(); //get folder contains a space separated list of the files/directories selected
                for(unsigned int i=0;i<m_ic.interps.size();i++)
                {
                    bool match=true; // all selected items must have names that match the wildcard for this grouping
                    wxString pathlist=paths;
                    wxString ipath=paths.BeforeFirst('*'); // '*' separated list
                    if(m_ic.interps[i].wildcards!=_T(""));
                        while(match && pathlist!=_T(""))
                        {
                            wxString name=wxFileName(ipath).GetFullName();
                            if(ipath!=_T("") && !WildCardListMatch(m_ic.interps[i].wildcards,ipath))
                                match=false;
                            pathlist=pathlist.AfterFirst('*');
                            ipath=pathlist.BeforeFirst('*');
                        }
                    if(match)
                    {
                        m_RunTarget=paths;
                        //TODO: need a m_TargetParent to allow the FileExplorer to define the parent of a selection (usually the root of the fileexplorer view?)
                        if(m_ic.interps[i].command.Find(_T("$mpaths"))>=0)
                        {
                            wxString menutext=m_ic.interps[i].name;
                            m_contextvec.Add(i);
                            AddModuleMenuEntry(menu,i,added);
                            added++;
                        }
                    }
                }
            }
            if(added>0)
                menu->InsertSeparator(sep_pos);
	    }
//	NotImplemented(_T("ShellExtensions::BuildModuleMenu()"));
}
예제 #17
0
// -------------------------------------------------------------------------------- //
guChannelEditor::guChannelEditor( wxWindow * parent, guPodcastChannel * channel ) :
    wxDialog( parent, wxID_ANY, _( "Podcast Channel Editor" ), wxDefaultPosition, wxSize( 564,329 ), wxDEFAULT_DIALOG_STYLE )
{
    wxStaticText* DescLabel;
    wxStaticText* AuthorLabel;
    wxStaticText* OwnerLabel;
    wxStaticText* DownloadLabel;
    wxStaticText* DeleteLabel;
    wxStdDialogButtonSizer* ButtonsSizer;
    wxButton* ButtonsSizerOK;
    wxButton* ButtonsSizerCancel;

    m_PodcastChannel = channel;

    guConfig * Config = ( guConfig * ) guConfig::Get();

	this->SetSizeHints( wxDefaultSize, wxDefaultSize );

	wxBoxSizer* MainSizer;
	MainSizer = new wxBoxSizer( wxVERTICAL );

	wxStaticBoxSizer* ChannelSizer;
	ChannelSizer = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, _( " Podcast Channel " ) ), wxVERTICAL );

	wxFlexGridSizer* FlexGridSizer;
    FlexGridSizer = new wxFlexGridSizer( 2, 0, 0 );
	FlexGridSizer->AddGrowableCol( 1 );
	FlexGridSizer->SetFlexibleDirection( wxBOTH );
	FlexGridSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );

	m_Image = new wxStaticBitmap( this, wxID_ANY, wxNullBitmap, wxDefaultPosition, wxSize( guPODCASTS_IMAGE_SIZE,guPODCASTS_IMAGE_SIZE ), 0 );
	FlexGridSizer->Add( m_Image, 0, wxALL, 5 );

    // Check that the directory to store podcasts are created
    wxString PodcastsPath = Config->ReadStr( CONFIG_KEY_PODCASTS_PATH, guPATH_PODCASTS, CONFIG_PATH_PODCASTS );
    wxFileName ImageFile = wxFileName( PodcastsPath + wxT( "/" ) +
                                       channel->m_Title + wxT( "/" ) +
                                       channel->m_Title + wxT( ".jpg" ) );
    if( ImageFile.Normalize( wxPATH_NORM_ALL | wxPATH_NORM_CASE ) )
    {
        wxImage PodcastImage;
        if( wxFileExists( ImageFile.GetFullPath() ) &&
            PodcastImage.LoadFile( ImageFile.GetFullPath() ) &&
            PodcastImage.IsOk() )
        {
            m_Image->SetBitmap( PodcastImage );
        }
        else
        {
            m_Image->SetBitmap( guBitmap( guIMAGE_INDEX_mid_podcast ) );
            if( !channel->m_Image.IsEmpty() )
            {
                guChannelUpdateImageThread * UpdateImageThread = new guChannelUpdateImageThread( this, channel->m_Image.c_str() );
                if( !UpdateImageThread )
                {
                    guLogError( wxT( "Could not create the Channel Image Thread" ) );
                }
            }
        }
    }

	m_Title = new wxStaticText( this, wxID_ANY, channel->m_Title, wxDefaultPosition, wxDefaultSize, 0 );
	FlexGridSizer->Add( m_Title, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );

	DescLabel = new wxStaticText( this, wxID_ANY, _( "Description:" ), wxDefaultPosition, wxDefaultSize, 0 );
	DescLabel->Wrap( -1 );
	DescLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );

	FlexGridSizer->Add( DescLabel, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );

	m_DescText = new wxStaticText( this, wxID_ANY, ( channel->m_Description.Length() > 200 ?
                        channel->m_Description.Mid( 0, 200 ) + wxT( " ..." ) :
                        channel->m_Description ), wxDefaultPosition, wxDefaultSize, 0 );
	m_DescText->Wrap( 450 );
	FlexGridSizer->Add( m_DescText, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );

	AuthorLabel = new wxStaticText( this, wxID_ANY, _("Author:"), wxDefaultPosition, wxDefaultSize, 0 );
	AuthorLabel->Wrap( -1 );
	AuthorLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );

	FlexGridSizer->Add( AuthorLabel, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );

	m_AuthorText = new wxStaticText( this, wxID_ANY, channel->m_Author, wxDefaultPosition, wxDefaultSize, 0 );
	m_AuthorText->Wrap( -1 );
	FlexGridSizer->Add( m_AuthorText, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT, 5 );

	OwnerLabel = new wxStaticText( this, wxID_ANY, _("Owner:"), wxDefaultPosition, wxDefaultSize, 0 );
	OwnerLabel->Wrap( -1 );
	OwnerLabel->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );

	FlexGridSizer->Add( OwnerLabel, 0, wxALIGN_RIGHT|wxBOTTOM|wxRIGHT|wxLEFT, 5 );

	m_OwnerText = new wxStaticText( this, wxID_ANY, channel->m_OwnerName +
                  wxT( " ( " ) + channel->m_OwnerEmail + wxT( " )" ) , wxDefaultPosition, wxDefaultSize, 0 );
	m_OwnerText->Wrap( -1 );
	FlexGridSizer->Add( m_OwnerText, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );

	DownloadLabel = new wxStaticText( this, wxID_ANY, _("Download:"), wxDefaultPosition, wxDefaultSize, 0 );
	DownloadLabel->Wrap( -1 );
	FlexGridSizer->Add( DownloadLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	wxBoxSizer* DownloadSizer;
	DownloadSizer = new wxBoxSizer( wxHORIZONTAL );

	wxString m_DownloadChoiceChoices[] = { _( "Manually" ), _( "Only if contains" ), _( "Everything" ) };
	int m_DownloadChoiceNChoices = sizeof( m_DownloadChoiceChoices ) / sizeof( wxString );
	m_DownloadChoice = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_DownloadChoiceNChoices, m_DownloadChoiceChoices, 0 );
	m_DownloadChoice->SetSelection( channel->m_DownloadType );
	DownloadSizer->Add( m_DownloadChoice, 0, wxTOP|wxBOTTOM|wxRIGHT, 5 );

	m_DownloadText = new wxTextCtrl( this, wxID_ANY, channel->m_DownloadText, wxDefaultPosition, wxDefaultSize, 0 );
	m_DownloadText->Enable( ( channel->m_DownloadType == guPODCAST_DOWNLOAD_FILTER ) );

	DownloadSizer->Add( m_DownloadText, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

	FlexGridSizer->Add( DownloadSizer, 1, wxEXPAND, 5 );

	DeleteLabel = new wxStaticText( this, wxID_ANY, _("Delete:"), wxDefaultPosition, wxDefaultSize, 0 );
	DeleteLabel->Wrap( -1 );
	FlexGridSizer->Add( DeleteLabel, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxBOTTOM|wxRIGHT|wxLEFT, 5 );

	m_DeleteCheckBox = new wxCheckBox( this, wxID_ANY, _( "Allow delete old items" ), wxDefaultPosition, wxDefaultSize, 0 );
	m_DeleteCheckBox->SetValue( channel->m_AllowDelete );

	FlexGridSizer->Add( m_DeleteCheckBox, 0, wxBOTTOM|wxRIGHT|wxALIGN_CENTER_VERTICAL, 5 );

	ChannelSizer->Add( FlexGridSizer, 1, wxEXPAND, 5 );

	MainSizer->Add( ChannelSizer, 1, wxEXPAND|wxALL, 5 );

	ButtonsSizer = new wxStdDialogButtonSizer();
	ButtonsSizerOK = new wxButton( this, wxID_OK );
	ButtonsSizer->AddButton( ButtonsSizerOK );
	ButtonsSizerCancel = new wxButton( this, wxID_CANCEL );
	ButtonsSizer->AddButton( ButtonsSizerCancel );
	ButtonsSizer->SetAffirmativeButton( ButtonsSizerOK );
	ButtonsSizer->SetCancelButton( ButtonsSizerCancel );
	ButtonsSizer->Realize();
	MainSizer->Add( ButtonsSizer, 0, wxEXPAND|wxBOTTOM|wxRIGHT|wxLEFT, 5 );

	this->SetSizer( MainSizer );
	this->Layout();

	ButtonsSizerOK->SetDefault();

    // Bind Events
    m_DownloadChoice->Bind( wxEVT_CHOICE, &guChannelEditor::OnDownloadChoice, this );
    Bind( guChannelEditorEvent, &guChannelEditor::OnChannelImageUpdated, this, guCHANNELEDITOR_EVENT_UPDATE_IMAGE );

    m_DescText->SetFocus();
}
예제 #18
0
/*! Starts the job running and sets the status code to STATUS_RUNNING.
 *
 * The posix implementation of this function uses the GMS helper script
 * provided with GAMESS to launch GAMESS. It does a simple fork and exec to
 * launch the script, and puts all the newly created processes in a process
 * group based on the original forked process.
 *
 * \sa mPid
 */
void PosixJob::Start()
{
	// try to find gamess
	wxString gamessname;
	if (gamessDir.IsEmpty()) {
		wxPathList SystemPath;
		SystemPath.AddEnvList(wxT("PATH"));
		gamessname = SystemPath.FindAbsoluteValidPath(wxT("gms"));
	} else {
		wxFileName name(gamessDir, wxT("gms"));
		name.MakeAbsolute();
		gamessname = name.GetFullPath();
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}

#ifdef DEFAULT_GAMESS_PATH
	if (gamessname.IsEmpty()) {
        wxStandardPaths & gStdPaths = wxStandardPaths::Get();
		gamessname = wxFileName(
				gStdPaths.GetExecutablePath()).GetPath() +
				wxT(DEFAULT_GAMESS_PATH) + wxT("/gms");
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}
#endif

	if (gamessname.IsEmpty()) {
		wxLogError(wxT("Could not find GAMESS"));
		mStatus = STATUS_ERROR;
		return;
	}

	wxString procs;
	procs << mNumProcessors;
	wxFileName name(mSpoolFileName);
	name.MakeRelativeTo(gamessDir);
	wxString input = name.GetFullPath();
	name.SetExt(wxT("log"));
	wxString logfile = name.GetFullPath();

	wxString command;
	command << wxT("Exec: ") << gamessname;
	command << wxT(" -n ") << procs;
	command << wxT(" -l ") << logfile;
	command << wxT(" ") << input;
	wxLogMessage(command);

	mPid = fork();
	if (mPid == 0) {
		wxSetWorkingDirectory(gamessDir);
		setpgid(0, 0);
		execl(gamessname.ToAscii(), gamessname.ToAscii(),
				"-n", (const char *)procs.ToAscii(),
				"-l", (const char *)logfile.ToAscii(),
				(const char *)input.ToAscii(), NULL);
		exit(1);
	}
	mStatus = STATUS_RUNNING;
}
예제 #19
0
bool Panel_Remaps::DoChangeImgDest( bool b_quiet, bool standalone)
{
	if( !paletteCtrl->b_init )
		return false;

	if( curr_remap == NULL )
		return false;

	//******************************
	// Get the new path
	wxString dest_obPath = txtctrl_destimg->GetValue();
	wxString _destPath = GetObFile( dest_obPath ).GetFullPath();
	if( _destPath == wxString() )
		b_quiet = true;

	//******************************
	// Make the change to the ob_object
	if( mode8bit )
	{
		wxString old_path = curr_remap->GetToken( 1 );
		if( old_path != dest_obPath )
		{
			entity->SetChanged();
			if( curr_remap->GetToken( 0 ) == wxString() )
				curr_remap->SetToken( 0, wxT("UNSETTED") );
			curr_remap->SetToken( 1, dest_obPath );
		}
	}
	else
	{
		// Set the palette tag
		wxString old_path = curr_remap->GetToken( 0 );
		if( old_path != dest_obPath )
		{
			entity->SetChanged();
			curr_remap->SetToken( 0, dest_obPath );
		}
	}

	//******************************
	// Undo the previous remapping
	paletteCtrl->UndoRemapping();

	bool res = false;

	//******************************
	// Check if the destination file exist
	if( ! wxFileName( _destPath ).FileExists() && !b_quiet )
		wxMessageBox( wxT("The Destination image for the remap doesn't exist")
		, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );

	else if( IsFileEmpty(_destPath) && !b_quiet )
		wxMessageBox( wxT("The Destination image for the remap is an empty file")
		, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );

	else if( ! wxImage( _destPath ).IsOk() && !b_quiet)
		wxMessageBox( wxT("Problem with the loading destination image of the remap")
		, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );

	else if( paletteCtrl->b_init )
	{
		res = paletteCtrl->InitRemapping_With( _destPath );
		if( ! res && !b_quiet)
			wxMessageBox(   wxT( "Problem with apply remapping between the two images\nAre they really fit each others ?")
			, wxT("ProPlem"), wxOK | wxICON_INFORMATION, this );

	}

	// Force refresh in case remapping didn"t work
	if( ! res )
		paletteCtrl->Refresh();

	if( standalone )
		Refresh();

	return res;
}
void KICAD_MANAGER_FRAME::OnLoadProject( wxCommandEvent& event )
{
    // Any open KIFACE's must be closed if they are not part of the new project.
    // (We never want a KIWAY_PLAYER open on a KIWAY that isn't in the same project.)
    // User is prompted here to close those KIWAY_PLAYERs:
    if( !Kiway.PlayersClose( false ) )
        return;

    // evt_id can be one of:
    //   ID_NEW_PROJECT, ID_NEW_PROJECT_FROM_TEMPLATE, ID_LOAD_PROJECT, and
    //   wxID_ANY from 3 different places.
    int evt_id = event.GetId();

    wxString    title;

    ClearMsg();

    bool newProject = ( evt_id == ID_NEW_PROJECT ) ||
                        ( evt_id == ID_NEW_PROJECT_FROM_TEMPLATE );

    if( evt_id != wxID_ANY )
    {
        int  style;

        if( newProject )
        {
            title = _( "Create New Project" );
            style = wxFD_SAVE | wxFD_OVERWRITE_PROMPT;
        }
        else
        {
            title = _( "Open Existing Project" );
            style = wxFD_OPEN | wxFD_FILE_MUST_EXIST;
        }

        wxString        default_dir = GetMruPath();
        wxFileDialog    dlg( this, title, default_dir, wxEmptyString,
                             ProjectFileWildcard, style );

        if( dlg.ShowModal() == wxID_CANCEL )
            return;

        //DBG( printf( "%s: wxFileDialog::GetPath=%s\n", __func__, TO_UTF8( dlg.GetPath() ) );)

        wxFileName pro( dlg.GetPath() );
        pro.SetExt( ProjectFileExtension );     // enforce extension

        if( !pro.IsAbsolute() )
            pro.MakeAbsolute();

        if( newProject )
        {
            // Check if the project directory is empty
            wxDir directory( pro.GetPath() );

            if( directory.HasFiles() )
            {
                wxString msg = _( "The selected directory is not empty.  We recommend you "
                                  "create projects in their own clean directory.\n\nDo you "
                                  "want to create a new empty directory for the project?" );

                if( IsOK( this, msg ) )
                {
                    // Append a new directory with the same name of the project file
                    // and try to create it
                    pro.AppendDir( pro.GetName() );

                    if( !wxMkdir( pro.GetPath() ) )
                        // There was a problem, undo
                        pro.RemoveLastDir();
                }
            }

            if( evt_id == ID_NEW_PROJECT )
            {
                CreateNewProject( pro.GetFullPath() );
            }
            else if( evt_id == ID_NEW_PROJECT_FROM_TEMPLATE )
            {
                // Launch the template selector dialog
                CreateNewProject( pro.GetFullPath(), true );
            }
        }

        SetProjectFileName( pro.GetFullPath() );
    }

    wxString prj_filename = GetProjectFileName();

    wxString nameless_prj = NAMELESS_PROJECT  wxT( ".pro" );

    wxLogDebug( wxT( "%s: %s" ),
                GetChars( wxFileName( prj_filename ).GetFullName() ),
                GetChars( nameless_prj ) );

    // Check if project file exists and if it is not noname.pro
    if( !wxFileExists( prj_filename )
      && !wxFileName( prj_filename ).GetFullName().IsSameAs( nameless_prj ) )
    {
        wxString msg = wxString::Format( _(
                "KiCad project file '%s' not found" ),
                GetChars( prj_filename ) );

        DisplayError( this, msg );
        return;
    }

    // Either this is the first time kicad has been run or one of the projects in the
    // history list is no longer valid.  This prevents kicad from automatically creating
    // a noname.pro file in the same folder as the kicad binary.
    if( wxFileName( prj_filename ).GetFullName().IsSameAs( nameless_prj ) && !newProject )
    {
        m_active_project = false;
        m_MessagesBox->SetValue( _( "To proceed, you can use the File menu to start a new project." ) );
        return;
    }
    else
    {
        m_active_project = true;
        m_MessagesBox->Clear();
    }

    Prj().ConfigLoad( PgmTop().SysSearch(), GeneralGroupName, s_KicadManagerParams );

    title = L"KiCad \u2014 " + prj_filename;

    if( !wxFileName( prj_filename ).IsDirWritable() )
        title += _( " [Read Only]" );
    else
        SetMruPath( Prj().GetProjectPath() );    // Only set MRU path if we have write access.

    SetTitle( title );

    if( !prj_filename.IsSameAs( nameless_prj ) )
        UpdateFileHistory( prj_filename, &PgmTop().GetFileHistory() );

    m_LeftWin->ReCreateTreePrj();

    // Rebuild the list of watched paths.
    // however this is possible only when the main loop event handler is running,
    // so we use it to run the rebuild function.
    wxCommandEvent cmd( wxEVT_COMMAND_MENU_SELECTED, ID_INIT_WATCHED_PATHS );

    wxPostEvent( this, cmd );

    PrintPrjInfo();
}
예제 #21
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

    std::string cfgFileName = getConfigFileName();
    wxFileName cfgFile = wxFileName(cfgFileName);

    if (!cfgFile.Exists()) {
        if (configName.length()) {
            wxFileName baseConfig = wxFileName(getConfigFileName(true));
            if (baseConfig.Exists()) {
                std::string baseConfigFileName = baseConfig.GetFullPath(wxPATH_NATIVE).ToStdString();
                std::cout << "Creating new configuration file '" << cfgFileName << "' by copying '" << baseConfigFileName << "'..";
                wxCopyFile(baseConfigFileName, cfgFileName);
                if (!cfgFile.Exists()) {
                    std::cout << "failed." << std::endl;
                    return true;
                }
                std::cout << "ok." << std::endl;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    if (cfgFile.IsFileReadable()) {
        std::cout << "Loading:: configuration file '" << cfgFileName << "'" << std::endl;

        cfg.LoadFromFileXML(cfgFileName);
    } else {
        std::cout << "Error loading:: configuration file '" << cfgFileName << "' is not readable!" << std::endl;
        return false;
    }

    if (cfg.rootNode()->hasAnother("window")) {
        int x = 0 ,y = 0 ,w = 0 ,h = 0;
        int max = 0 ,tips = 0 ,perf_mode = 0 ,mpc = 0;
        
        DataNode *win_node = cfg.rootNode()->getNext("window");
        
        if (win_node->hasAnother("w") && win_node->hasAnother("h") && win_node->hasAnother("x") && win_node->hasAnother("y")) {

            win_node->getNext("x")->element()->get(x);
            win_node->getNext("y")->element()->get(y);
            win_node->getNext("w")->element()->get(w);
            win_node->getNext("h")->element()->get(h);
            
            winX.store(x);
            winY.store(y);
            winW.store(w);
            winH.store(h);
        }
        
        if (win_node->hasAnother("max")) {
            win_node->getNext("max")->element()->get(max);
            winMax.store(max?true:false);
        }

        if (win_node->hasAnother("tips")) {
            win_node->getNext("tips")->element()->get(tips);
            showTips.store(tips?true:false);
        }

        // default:
        perfMode.store(PERF_NORMAL);

        if (win_node->hasAnother("perf_mode")) {
            win_node->getNext("perf_mode")->element()->get(perf_mode);

            if (perf_mode == (int)PERF_LOW) {
                perfMode.store(PERF_LOW);
            } else if (perf_mode == (int)PERF_HIGH) {
                perfMode.store(PERF_HIGH);
            }
        }
       
        if (win_node->hasAnother("theme")) {
            int theme;
            win_node->getNext("theme")->element()->get(theme);
            themeId.store(theme);
        }

        if (win_node->hasAnother("font_scale")) {
            int fscale;
            win_node->getNext("font_scale")->element()->get(fscale);
            fontScale.store(fscale);
        }

        if (win_node->hasAnother("snap")) {
			long long snapVal;
			win_node->getNext("snap")->element()->get(snapVal);
			snap.store(snapVal);
		}

        if (win_node->hasAnother("center_freq")) {
            long long freqVal;
            win_node->getNext("center_freq")->element()->get(freqVal);
            centerFreq.store(freqVal);
        }

        if (win_node->hasAnother("waterfall_lps")) {
            int lpsVal;
            win_node->getNext("waterfall_lps")->element()->get(lpsVal);
            waterfallLinesPerSec.store(lpsVal);
        }
        
        if (win_node->hasAnother("spectrum_avg")) {
            float avgVal;
            win_node->getNext("spectrum_avg")->element()->get(avgVal);
            spectrumAvgSpeed.store(avgVal);
        }

        if (win_node->hasAnother("modemprops_collapsed")) {
            win_node->getNext("modemprops_collapsed")->element()->get(mpc);
            modemPropsCollapsed.store(mpc?true:false);
        }
        
        if (win_node->hasAnother("db_offset")) {
            DataNode *offset_node = win_node->getNext("db_offset");
            int offsetValue = 0;
            offset_node->element()->get(offsetValue);
            setDBOffset(offsetValue);
        }

        if (win_node->hasAnother("main_split")) {
            float gVal;
            win_node->getNext("main_split")->element()->get(gVal);
            mainSplit.store(gVal);
        }
        
        if (win_node->hasAnother("vis_split")) {
            float gVal;
            win_node->getNext("vis_split")->element()->get(gVal);
            visSplit.store(gVal);
        }
        
        if (win_node->hasAnother("bookmark_split")) {
            float gVal;
            win_node->getNext("bookmark_split")->element()->get(gVal);
            bookmarkSplit.store(gVal);
        }

        if (win_node->hasAnother("bookmark_visible")) {
            int bVal;
            win_node->getNext("bookmark_visible")->element()->get(bVal);
            bookmarksVisible.store(bVal);
        }
    }
    
	//Recording settings:
    if (cfg.rootNode()->hasAnother("recording")) {
        DataNode *rec_node = cfg.rootNode()->getNext("recording");

        if (rec_node->hasAnother("path")) {
            DataNode *rec_path = rec_node->getNext("path");
            recordingPath = rec_path->element()->toString();
        }

		if (rec_node->hasAnother("squelch")) {
			DataNode *rec_squelch = rec_node->getNext("squelch");
			rec_squelch->element()->get(recordingSquelchOption);
		}

		if (rec_node->hasAnother("file_time_limit")) {
			DataNode *rec_file_time_limit = rec_node->getNext("file_time_limit");
			rec_file_time_limit->element()->get(recordingFileTimeLimitSeconds);
		}
    }
    
    if (cfg.rootNode()->hasAnother("devices")) {
        DataNode *devices_node = cfg.rootNode()->getNext("devices");

        while (devices_node->hasAnother("device")) {
            DataNode *device_node = devices_node->getNext("device");
            if (device_node->hasAnother("id")) {
                std::string deviceId = device_node->getNext("id")->element()->toString();

                getDevice(deviceId)->load(device_node);
            }
        }
    }
    
    if (cfg.rootNode()->hasAnother("manual_devices")) {
        DataNode *manuals_node = cfg.rootNode()->getNext("manual_devices");
        
        while (manuals_node->hasAnother("device")) {
            DataNode *manual_node = manuals_node->getNext("device");
            if (manual_node->hasAnother("factory") && manual_node->hasAnother("params")) {
                SDRManualDef mdef;
                
                mdef.factory = manual_node->getNext("factory")->element()->toString();
                mdef.params = manual_node->getNext("params")->element()->toString();

                manualDevices.push_back(mdef);
            }
        }
    }
    
#ifdef USE_HAMLIB
    if (cfg.rootNode()->hasAnother("rig")) {
        DataNode *rig_node = cfg.rootNode()->getNext("rig");

        if (rig_node->hasAnother("enabled")) {
            int loadEnabled;
            rig_node->getNext("enabled")->element()->get(loadEnabled);
            rigEnabled.store(loadEnabled?true:false);
        }
        if (rig_node->hasAnother("model")) {
            int loadModel;
            rig_node->getNext("model")->element()->get(loadModel);
            rigModel.store(loadModel?loadModel:1);
        }
        if (rig_node->hasAnother("rate")) {
            int loadRate;
            rig_node->getNext("rate")->element()->get(loadRate);
            rigRate.store(loadRate?loadRate:57600);
        }
        if (rig_node->hasAnother("port")) {
            rigPort = rig_node->getNext("port")->element()->toString();
        }
        if (rig_node->hasAnother("control")) {
            int loadControl;
            rig_node->getNext("control")->element()->get(loadControl);
            rigControlMode.store(loadControl?true:false);
        }
        if (rig_node->hasAnother("follow")) {
            int loadFollow;
            rig_node->getNext("follow")->element()->get(loadFollow);
            rigFollowMode.store(loadFollow?true:false);
        }
        if (rig_node->hasAnother("center_lock")) {
            int loadCenterLock;
            rig_node->getNext("center_lock")->element()->get(loadCenterLock);
            rigCenterLock.store(loadCenterLock?true:false);
        }
        if (rig_node->hasAnother("follow_modem")) {
            int loadFollow;
            rig_node->getNext("follow_modem")->element()->get(loadFollow);
            rigFollowModem.store(loadFollow?true:false);
        }
    }
#endif


    return true;
}
예제 #22
0
wxString wxGtkFileChooser::GetFilename() const
{
    return wxFileName( GetPath() ).GetFullName();
}
예제 #23
0
파일: ed2khash.cpp 프로젝트: geekt/amule
/// Set Ed2k hash from a file
bool Ed2kHash::SetED2KHashFromFile(const wxString& filename, MD4Hook hook)
{
  return SetED2KHashFromFile(wxFileName(filename), hook);
}
예제 #24
0
파일: ifacecheck.cpp 프로젝트: beanhome/dev
bool IfaceCheckApp::Compare()
{
    const wxClassArray& interfaces = m_doxyInterface.GetClasses();
    const wxClass* c;
    int mcount = 0, ccount = 0;

    wxLogMessage("Comparing the interface API to the real API (%d classes to compare)...",
                 interfaces.GetCount());

    if (!m_strToMatch.IsEmpty())
    {
        wxLogMessage("Processing only header files matching '%s' expression.", m_strToMatch);
    }

    for (unsigned int i=0; i<interfaces.GetCount(); i++)
    {
        // only compare the methods which are available for the port
        // for which the gcc XML was produced
        if (interfaces[i].GetAvailability() != wxPORT_UNKNOWN &&
            (interfaces[i].GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {

            if (g_verbose)
            {
                wxLogMessage("skipping class '%s' since it's not available for the %s port.",
                           interfaces[i].GetName(), m_gccInterface.GetInterfacePortName());
            }

            continue;       // skip this method
        }

        // shorten the name of the header so the log file is more readable
        // and also for calling IsToProcess() against it
        wxString header = wxFileName(interfaces[i].GetHeader()).GetFullName();

        if (!IsToProcess(header))
            continue;       // skip this one

        wxString cname = interfaces[i].GetName();

        // search in the real headers for i-th interface class; we search for
        // both class cname and cnameBase since in wxWidgets world tipically
        // class cname is platform-specific while the real public interface of
        // that class is part of the cnameBase class.
        /*c = m_gccInterface.FindClass(cname + "Base");
        if (c) api.Add(c);*/

        c = m_gccInterface.FindClass(cname);
        if (!c)
        {
            // sometimes the platform-specific class is named "wxGeneric" + cname
            // or similar:
            c = m_gccInterface.FindClass("wxGeneric" + cname.Mid(2));
            if (!c)
            {
                c = m_gccInterface.FindClass("wxGtk" + cname.Mid(2));
            }
        }

        if (c) {

            // there is a class with the same (logic) name!
            mcount += CompareClasses(&interfaces[i], c);

        } else {

            wxLogMessage("%s: couldn't find the real interface for the '%s' class",
                       header, cname);
            ccount++;
        }
    }

    wxLogMessage("%d on a total of %d methods (%.1f%%) of the interface headers do not exist in the real headers",
               mcount, m_doxyInterface.GetMethodCount(), (float)(100.0 * mcount/m_doxyInterface.GetMethodCount()));
    wxLogMessage("%d on a total of %d classes (%.1f%%) of the interface headers do not exist in the real headers",
               ccount, m_doxyInterface.GetClassesCount(), (float)(100.0 * ccount/m_doxyInterface.GetClassesCount()));

    return true;
}
예제 #25
0
파일: stdpaths.cpp 프로젝트: gitrider/wxsj2
wxString wxStandardPaths::GetDataDir() const
{
    // under Windows each program is usually installed in its own directory and
    // so its datafiles are in the same directory as its main executable
    return wxFileName(wxGetFullModuleName()).GetPath();
}
예제 #26
0
파일: ifacecheck.cpp 프로젝트: beanhome/dev
int IfaceCheckApp::CompareClasses(const wxClass* iface, const wxClass* api)
{
    const wxMethod *real;
    int count = 0;

    wxASSERT(iface && api);

    // shorten the name of the header so the log file is more readable
    wxString header = wxFileName(iface->GetHeader()).GetFullName();

    for (unsigned int i=0; i<iface->GetMethodCount(); i++)
    {
        const wxMethod& m = iface->GetMethod(i);

        // only compare the methods which are available for the port
        // for which the gcc XML was produced
        if (m.GetAvailability() != wxPORT_UNKNOWN &&
            (m.GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {

            if (g_verbose)
            {
                wxLogMessage("skipping method '%s' since it's not available for the %s port.",
                           m.GetAsString(), m_gccInterface.GetInterfacePortName());
            }

            continue;       // skip this method
        }

        // search in the methods of the api classes provided
        real = api->RecursiveUpwardFindMethod(m, &m_gccInterface);

        // avoid some false positives:
        if (!real && m.ActsAsDefaultCtor())
        {
            // build an artificial default ctor for this class:
            wxMethod temp(m);
            temp.GetArgumentTypes().Clear();

            // repeat search:
            real = api->RecursiveUpwardFindMethod(temp, &m_gccInterface);
        }

        // no matches?
        if (!real)
        {
            bool proceed = true;
            wxMethodPtrArray overloads =
                api->RecursiveUpwardFindMethodsNamed(m.GetName(), &m_gccInterface);

            // avoid false positives:
            for (unsigned int k=0; k<overloads.GetCount(); k++)
                if (overloads[k]->MatchesExceptForAttributes(m) &&
                    m.IsDeprecated() && !overloads[k]->IsDeprecated())
                {
                    // maybe the iface method is marked as deprecated but the
                    // real method is not?
                    wxMethod tmp(*overloads[k]);
                    tmp.SetDeprecated(true);

                    if (tmp == m)
                    {
                        // in this case, we can disregard this warning... the real
                        // method probably is included in WXWIN_COMPAT sections!
                        proceed = false;    // skip this method
                    }
                }

#define HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES        0
#if HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES
            for (unsigned int k=0; k<overloads.GetCount(); k++)
                if (overloads[k]->MatchesExceptForAttributes(m))
                {
                    // fix default values of results[k]:
                    wxMethod tmp(*overloads[k]);
                    tmp.SetArgumentTypes(m.GetArgumentTypes());

                    // modify interface header
                    if (FixMethod(iface->GetHeader(), &m, &tmp))
                    {
                        wxLogMessage("Adjusted attributes of '%s' method", m.GetAsString());
                    }

                    proceed = false;
                    break;
                }
#endif // HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES

            if (proceed)
            {
                if (overloads.GetCount()==0)
                {
                    wxLogMessage("%s: real '%s' class and their parents have no method '%s'",
                                header, api->GetName(), m.GetAsString());
                    // we've found no overloads
                }
                else
                {
                    // first, output a warning
                    wxString warning = header;
                    if (overloads.GetCount()>1)
                        warning += wxString::Format(": in the real headers there are %d overloads of '%s' for "
                                                    "'%s' all with different signatures:\n",
                                                    overloads.GetCount(), m.GetName(), api->GetName());
                    else {
                        warning += wxString::Format(": in the real headers there is a method '%s' for '%s'"
                                                    " but has different signature:\n",
                                                    m.GetName(), api->GetName());
                    }

                    // get a list of the prototypes with _all_ possible attributes:
                    warning += "\tdoxy header: " + m.GetAsString(true, true, true, true);
                    for (unsigned int j=0; j<overloads.GetCount(); j++)
                        warning += "\n\treal header: " + overloads[j]->GetAsString(true, true, true, true);

                    wxLogWarning("%s", warning);
                    count++;

                    if (overloads.GetCount()>1)
                    {
                        // TODO: decide which of these overloads is the most "similar" to m
                        //       and eventually modify it
                        if (m_modify)
                        {
                            wxLogWarning("\tmanual fix is required");
                        }
                    }
                    else
                    {
                        wxASSERT(overloads.GetCount() == 1);

                        if (m_modify || m.IsCtor())
                        {
                            wxLogWarning("\tfixing it...");

                            // try to modify it!
                            FixMethod(iface->GetHeader(), &m, overloads[0]);
                        }
                    }
                }

                count++;
            }       // if (proceed)
        }
    }

    return count;
}
예제 #27
0
void AppCoreThread::ApplySettings( const Pcsx2Config& src )
{
	// 'fixup' is the EmuConfig we're going to upload to the emulator, which very well may
	// differ from the user-configured EmuConfig settings.  So we make a copy here and then
	// we apply the commandline overrides and database gamefixes, and then upload 'fixup'
	// to the global EmuConfig.
	//
	// Note: It's important that we apply the commandline overrides *before* database fixes.
	// The database takes precedence (if enabled).

	Pcsx2Config fixup( src );

	const CommandlineOverrides& overrides( wxGetApp().Overrides );
	if( overrides.DisableSpeedhacks || !g_Conf->EnableSpeedHacks )
		fixup.Speedhacks.DisableAll();

	if( overrides.ApplyCustomGamefixes )
	{
		for (GamefixId id=GamefixId_FIRST; id < pxEnumEnd; ++id)
			fixup.Gamefixes.Set( id, overrides.Gamefixes.Get(id) );
	}
	else if( !g_Conf->EnableGameFixes )
		fixup.Gamefixes.DisableAll();

	wxString gameCRC;
	wxString gameSerial;
	wxString gamePatch;
	wxString gameFixes;
	wxString gameCheats;
	wxString gameWsHacks;

	wxString gameName;
	wxString gameCompat;
	wxString gameMemCardFilter;

	int numberLoadedCheats;
	int numberLoadedWideScreenPatches;
	int numberDbfCheatsLoaded;

	if (ElfCRC) gameCRC.Printf( L"%8.8x", ElfCRC );
	if (!DiscSerial.IsEmpty()) gameSerial = L" [" + DiscSerial  + L"]";

	const wxString newGameKey( SysGetDiscID() );
	const bool verbose( newGameKey != curGameKey );
	SetupPatchesCon(verbose);

	curGameKey = newGameKey;

	if (!curGameKey.IsEmpty())
	{
		if (IGameDatabase* GameDB = AppHost_GetGameDatabase() )
		{
			Game_Data game;
			if (GameDB->findGame(game, curGameKey)) {
				int compat = game.getInt("Compat");
				gameName   = game.getString("Name");
				gameName  += L" (" + game.getString("Region") + L")";
				gameCompat = L" [Status = "+compatToStringWX(compat)+L"]";
				gameMemCardFilter = game.getString("MemCardFilter");
			}

			if (EmuConfig.EnablePatches) {
				if (int patches = InitPatches(gameCRC, game)) {
					gamePatch.Printf(L" [%d Patches]", patches);
					PatchesCon->WriteLn(Color_Green, "(GameDB) Patches Loaded: %d", patches);
				}
				if (int fixes = loadGameSettings(fixup, game)) {
					gameFixes.Printf(L" [%d Fixes]", fixes);
				}
			}
		}
	}

	if (!gameMemCardFilter.IsEmpty()) {
		sioSetGameSerial(gameMemCardFilter);
	} else {
		sioSetGameSerial(curGameKey);
	}

	if (gameName.IsEmpty() && gameSerial.IsEmpty() && gameCRC.IsEmpty())
	{
		// if all these conditions are met, it should mean that we're currently running BIOS code.
		// Chances are the BiosChecksum value is still zero or out of date, however -- because
		// the BIos isn't loaded until after initial calls to ApplySettings.

		gameName = L"Booting PS2 BIOS... ";
	}

	ResetCheatsCount();

	//Till the end of this function, entry CRC will be 00000000
	if (!gameCRC.Length()) {
		if (EmuConfig.EnableWideScreenPatches || EmuConfig.EnableCheats) {
			Console.WriteLn(Color_Gray, "Patches: No CRC, using 00000000 instead.");
		}
		gameCRC = L"00000000";
	}

	// regular cheat patches
	if (EmuConfig.EnableCheats) {
		if (numberLoadedCheats = LoadCheats(gameCRC, GetCheatsFolder(), L"Cheats")) {
			gameCheats.Printf(L" [%d Cheats]", numberLoadedCheats);
		}
	}

	// wide screen patches
	if (EmuConfig.EnableWideScreenPatches) {
		if (numberLoadedWideScreenPatches = LoadCheats(gameCRC, GetCheatsWsFolder(), L"Widescreen hacks")) {
			gameWsHacks.Printf(L" [%d widescreen hacks]", numberLoadedWideScreenPatches);
		}
		else {
			// No ws cheat files found at the cheats_ws folder, try the ws cheats zip file.
			wxString cheats_ws_archive = Path::Combine(PathDefs::GetProgramDataDir(), wxFileName(L"cheats_ws.zip"));

			if (numberDbfCheatsLoaded = LoadCheatsFromZip(gameCRC, cheats_ws_archive)) {
				PatchesCon->WriteLn(Color_Green, "(Wide Screen Cheats DB) Patches Loaded: %d", numberDbfCheatsLoaded);
				gameWsHacks.Printf(L" [%d widescreen hacks]", numberDbfCheatsLoaded);
			}
		}
	}

	wxString consoleTitle = gameName + gameSerial;
	if (!gameSerial.IsEmpty()) {
		consoleTitle += L" [" + gameCRC.MakeUpper() + L"]";
	}
	consoleTitle += gameCompat + gameFixes + gamePatch + gameCheats + gameWsHacks;

	Console.SetTitle(consoleTitle);

	// Re-entry guard protects against cases where code wants to manually set core settings
	// which are not part of g_Conf.  The subsequent call to apply g_Conf settings (which is
	// usually the desired behavior) will be ignored.

	static int localc = 0;
	RecursionGuard guard( localc );
	if( guard.IsReentrant() ) return;
	if( fixup == EmuConfig ) return;

	if( m_ExecMode >= ExecMode_Opened )
	{
		ScopedCoreThreadPause paused_core;
		_parent::ApplySettings( fixup );
		paused_core.AllowResume();
	}
	else
	{
		_parent::ApplySettings( fixup );
	}
}
예제 #28
0
int ExportFLAC::Export(AudacityProject *project,
                        int numChannels,
                        wxString fName,
                        bool selectionOnly,
                        double t0,
                        double t1,
                        MixerSpec *mixerSpec,
                        Tags *metadata,
                        int WXUNUSED(subformat))
{
   double    rate    = project->GetRate();
   TrackList *tracks = project->GetTracks();

   wxLogNull logNo;            // temporarily disable wxWidgets error messages
   int updateResult = eProgressSuccess;

   int levelPref;
   gPrefs->Read(wxT("/FileFormats/FLACLevel"), &levelPref, 5);

   wxString bitDepthPref =
      gPrefs->Read(wxT("/FileFormats/FLACBitDepth"), wxT("16"));

   FLAC::Encoder::File encoder;

#ifdef LEGACY_FLAC
   encoder.set_filename(OSOUTPUT(fName));
#endif
   encoder.set_channels(numChannels);
   encoder.set_sample_rate(lrint(rate));

   // See note in GetMetadata() about a bug in libflac++ 1.1.2
   if (!GetMetadata(project, metadata)) {
      return false;
   }

   if (mMetadata) {
      encoder.set_metadata(&mMetadata, 1);
   }

   sampleFormat format;
   if (bitDepthPref == wxT("24")) {
      format = int24Sample;
      encoder.set_bits_per_sample(24);
   } else { //convert float to 16 bits
      format = int16Sample;
      encoder.set_bits_per_sample(16);
   }

   // Duplicate the flac command line compression levels
   if (levelPref < 0 || levelPref > 8) {
      levelPref = 5;
   }
   encoder.set_do_exhaustive_model_search(flacLevels[levelPref].do_exhaustive_model_search);
   encoder.set_do_escape_coding(flacLevels[levelPref].do_escape_coding);
   if (numChannels != 2) {
      encoder.set_do_mid_side_stereo(false);
      encoder.set_loose_mid_side_stereo(false);
   }
   else {
      encoder.set_do_mid_side_stereo(flacLevels[levelPref].do_mid_side_stereo);
      encoder.set_loose_mid_side_stereo(flacLevels[levelPref].loose_mid_side_stereo);
   }
   encoder.set_qlp_coeff_precision(flacLevels[levelPref].qlp_coeff_precision);
   encoder.set_min_residual_partition_order(flacLevels[levelPref].min_residual_partition_order);
   encoder.set_max_residual_partition_order(flacLevels[levelPref].max_residual_partition_order);
   encoder.set_rice_parameter_search_dist(flacLevels[levelPref].rice_parameter_search_dist);
   encoder.set_max_lpc_order(flacLevels[levelPref].max_lpc_order);

#ifdef LEGACY_FLAC
   encoder.init();
#else
   wxFFile f;     // will be closed when it goes out of scope
   if (!f.Open(fName, wxT("w+b"))) {
      wxMessageBox(wxString::Format(_("FLAC export couldn't open %s"), fName.c_str()));
      return false;
   }

   // Even though there is an init() method that takes a filename, use the one that
   // takes a file handle because wxWidgets can open a file with a Unicode name and
   // libflac can't (under Windows).
   int status = encoder.init(f.fp());
   if (status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
      wxMessageBox(wxString::Format(_("FLAC encoder failed to initialize\nStatus: %d"), status));
      return false;
   }
#endif

   if (mMetadata) {
      ::FLAC__metadata_object_delete(mMetadata);
   }

   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(selectionOnly, &numWaveTracks, &waveTracks);
   Mixer *mixer = CreateMixer(numWaveTracks, waveTracks,
                            tracks->GetTimeTrack(),
                            t0, t1,
                            numChannels, SAMPLES_PER_RUN, false,
                            rate, format, true, mixerSpec);
   delete [] waveTracks;

   int i, j;
   FLAC__int32 **tmpsmplbuf = new FLAC__int32*[numChannels];
   for (i = 0; i < numChannels; i++) {
      tmpsmplbuf[i] = (FLAC__int32 *) calloc(SAMPLES_PER_RUN, sizeof(FLAC__int32));
   }

   {
      ProgressDialog progress(wxFileName(fName).GetName(),
         selectionOnly ?
         _("Exporting the selected audio as FLAC") :
         _("Exporting the entire project as FLAC"));

      while (updateResult == eProgressSuccess) {
         sampleCount samplesThisRun = mixer->Process(SAMPLES_PER_RUN);
         if (samplesThisRun == 0) { //stop encoding
            break;
         }
         else {
            for (i = 0; i < numChannels; i++) {
               samplePtr mixed = mixer->GetBuffer(i);
               if (format == int24Sample) {
                  for (j = 0; j < samplesThisRun; j++) {
                     tmpsmplbuf[i][j] = ((int *)mixed)[j];
                  }
               }
               else {
                  for (j = 0; j < samplesThisRun; j++) {
                     tmpsmplbuf[i][j] = ((short *)mixed)[j];
                  }
               }
            }
            encoder.process(tmpsmplbuf, samplesThisRun);
         }
         updateResult = progress.Update(mixer->MixGetCurrentTime() - t0, t1 - t0);
      }
      f.Detach(); // libflac closes the file
      encoder.finish();
   }

   for (i = 0; i < numChannels; i++) {
      free(tmpsmplbuf[i]);
   }
   delete mixer;

   delete[] tmpsmplbuf;

   return updateResult;
}
예제 #29
0
String directoryName(const String& path)
{
    return wxFileName(path).GetPath();
}
예제 #30
0
bool NewBuildTab::DoSelectAndOpen(int buildViewLine, bool centerLine)
{
    if(!m_viewData.count(buildViewLine)) {
        return false;
    }

    BuildLineInfo* bli = m_viewData.find(buildViewLine)->second;
    if(bli) {
        wxFileName fn(bli->GetFilename());

        // Highlight the clicked line on the view
        m_view->MarkerDeleteAll(LEX_GCC_MARKER);
        m_view->MarkerAdd(bli->GetLineInBuildTab(), LEX_GCC_MARKER);

        if(!fn.IsAbsolute()) {
            std::vector<wxFileName> files;
            std::vector<wxFileName> candidates;
            ManagerST::Get()->GetWorkspaceFiles(files, true);

            for(size_t i = 0; i < files.size(); ++i) {
                if(files.at(i).GetFullName() == fn.GetFullName()) {
                    candidates.push_back(files.at(i));
                }
            }

            if(candidates.empty()) return false;

            if(candidates.size() == 1)
                fn = candidates.at(0);

            else {
                // prompt the user
                wxArrayString fileArr;
                for(size_t i = 0; i < candidates.size(); ++i) {
                    fileArr.Add(candidates.at(i).GetFullPath());
                }

                clSingleChoiceDialog dlg(EventNotifier::Get()->TopFrame(), fileArr);
                dlg.SetLabel(_("Select a file to open"));
                if(dlg.ShowModal() != wxID_OK) return false;

                wxString selection = dlg.GetSelection();
                if(selection.IsEmpty()) return false;

                fn = wxFileName(selection);
                // if we resolved it now, open the file there is no point in searching this file
                // in m_buildInfoPerFile since the key on this map is kept as full name
                LEditor* editor = clMainFrame::Get()->GetMainBook()->FindEditor(fn.GetFullPath());
                if(!editor) {
                    editor = clMainFrame::Get()->GetMainBook()->OpenFile(
                        fn.GetFullPath(), wxT(""), bli->GetLineNumber(), wxNOT_FOUND, OF_AddJump);
                }

                if(editor) {
                    DoCentreErrorLine(bli, editor, centerLine);
                    return true;
                }
            }
        }

        if(fn.IsAbsolute()) {

            // try to locate the editor first
            LEditor* editor = clMainFrame::Get()->GetMainBook()->FindEditor(fn.GetFullPath());
            if(!editor) {
                // Open it
                editor = clMainFrame::Get()->GetMainBook()->OpenFile(
                    bli->GetFilename(), wxT(""), bli->GetLineNumber(), wxNOT_FOUND, OF_AddJump);
            }

            if(editor) {
                if(!editor->HasCompilerMarkers()) MarkEditor(editor);

                int lineNumber = bli->GetLineNumber();
                if(lineNumber > 0) {
                    lineNumber--;
                }

                DoCentreErrorLine(bli, editor, centerLine);
                return true;
            }
        }
    }
    return false;
}