bool DIALOG_PAGES_SETTINGS::SavePageSettings()
{
    bool retSuccess = false;

    wxString fileName = GetWksFileName();

    if( fileName != BASE_SCREEN::m_PageLayoutDescrFileName )
    {
        wxString fullFileName =
                    WORKSHEET_LAYOUT::MakeFullFileName( fileName, m_projectPath );

        if( !fullFileName.IsEmpty() )
        {

            if( !wxFileExists( fullFileName ) )
            {
                wxString msg;
                msg.Printf( _("Page layout description file <%s> not found. Abort"),
                            GetChars( fullFileName ) );
                wxMessageBox( msg );
                return false;
            }
        }

        BASE_SCREEN::m_PageLayoutDescrFileName = fileName;
        WORKSHEET_LAYOUT& pglayout = WORKSHEET_LAYOUT::GetTheInstance();
        pglayout.SetPageLayout( fullFileName );
        m_localPrjConfigChanged = true;
    }

    int idx = m_paperSizeComboBox->GetSelection();

    if( idx < 0 )
        idx = 0;

    const wxString paperType = m_pageFmt[idx];

    if( paperType.Contains( PAGE_INFO::Custom ) )
    {
        GetCustomSizeMilsFromDialog();

        retSuccess = m_pageInfo.SetType( PAGE_INFO::Custom );

        if( retSuccess )
        {
            if( m_layout_size.x < MIN_PAGE_SIZE || m_layout_size.y < MIN_PAGE_SIZE ||
                m_layout_size.x > MAX_PAGE_SIZE || m_layout_size.y > MAX_PAGE_SIZE )
            {
                wxString msg = wxString::Format( _( "Selected custom paper size\nis out of the permissible \
limits\n%.1f - %.1f %s!\nSelect another custom paper size?" ),
                        g_UserUnit == INCHES ? MIN_PAGE_SIZE / 1000. : MIN_PAGE_SIZE * 25.4 / 1000,
                        g_UserUnit == INCHES ? MAX_PAGE_SIZE / 1000. : MAX_PAGE_SIZE * 25.4 / 1000,
                        g_UserUnit == INCHES ? _( "inches" ) : _( "mm" ) );

                if( wxMessageBox( msg, _( "Warning!" ), wxYES_NO | wxICON_EXCLAMATION, this ) == wxYES )
                {
                    return false;
                }

                m_layout_size.x = Clamp( MIN_PAGE_SIZE, m_layout_size.x, MAX_PAGE_SIZE );
                m_layout_size.y = Clamp( MIN_PAGE_SIZE, m_layout_size.y, MAX_PAGE_SIZE );
            }

            PAGE_INFO::SetCustomWidthMils( m_layout_size.x );
            PAGE_INFO::SetCustomHeightMils( m_layout_size.y );

            m_pageInfo.SetWidthMils( m_layout_size.x );
            m_pageInfo.SetHeightMils( m_layout_size.y );
        }
Esempio n. 2
0
bool usImage::Load(const wxString& fname)
{
    bool bError = false;

    try
    {
        if (!wxFileExists(fname))
        {
            pFrame->Alert(_("File does not exist - cannot load ") + fname);
            throw ERROR_INFO("File does not exist");
        }

        int status = 0;  // CFITSIO status value MUST be initialized to zero!
        fitsfile *fptr;  // FITS file pointer
        if (!PHD_fits_open_diskfile(&fptr, fname, READONLY, &status))
        {
            int hdutype;
            if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU)
            {
                pFrame->Alert(_("FITS file is not of an image: ") + fname);
                throw ERROR_INFO("Fits file is not an image");
            }

            // Get HDUs and size
            int naxis = 0;
            fits_get_img_dim(fptr, &naxis, &status);
            long fsize[3];
            fits_get_img_size(fptr, 2, fsize, &status);
            int nhdus = 0;
            fits_get_num_hdus(fptr, &nhdus, &status);
            if ((nhdus != 1) || (naxis != 2)) {
                pFrame->Alert(_("Unsupported type or read error loading FITS file ") + fname);
                throw ERROR_INFO("unsupported type");
            }
            if (Init((int) fsize[0], (int) fsize[1]))
            {
                pFrame->Alert(_("Memory allocation error loading FITS file ") + fname);
                throw ERROR_INFO("Memory Allocation failure");
            }
            long fpixel[3] = { 1, 1, 1 };
            if (fits_read_pix(fptr, TUSHORT, fpixel, (int)(fsize[0] * fsize[1]), NULL, ImageData, NULL, &status)) { // Read image
                pFrame->Alert(_("Error reading data from FITS file ") + fname);
                throw ERROR_INFO("Error reading");
            }

            char *key = const_cast<char *>("EXPOSURE");
            float exposure;
            status = 0;
            fits_read_key(fptr, TFLOAT, key, &exposure, NULL, &status);
            if (status == 0)
                ImgExpDur = (int) (exposure * 1000.0);

            key = const_cast<char *>("STACKCNT");
            int stackcnt;
            status = 0;
            fits_read_key(fptr, TINT, key, &stackcnt, NULL, &status);
            if (status == 0)
                ImgStackCnt = (int) stackcnt;

            PHD_fits_close_file(fptr);
        }
        else
        {
            pFrame->Alert(_("Error opening FITS file ") + fname);
            throw ERROR_INFO("error opening file");
        }
    }
    catch (wxString Msg)
    {
        POSSIBLY_UNUSED(Msg);
        bError = true;
    }

    return bError;
}
bool PluginManager::UninstallPlugin(cbPlugin* plugin, bool removeFiles)
{
    if (!plugin)
        return false;

    wxString title;
    wxString pluginFilename;
    wxString resourceFilename;
    wxString settingsOnFilename;
    wxString settingsOffFilename;
    wxArrayString extrafiles;

    // find the plugin element
    for (size_t i = 0; i < m_Plugins.GetCount(); ++i)
    {
        PluginElement* elem = m_Plugins[i];
        if (elem && elem->plugin == plugin)
        {
            // got it
            title = elem->info.title;
            pluginFilename = elem->fileName;
            // now get the resource name
            wxFileName fname(pluginFilename);
            resourceFilename = fname.GetName() + _T(".zip");
            settingsOnFilename = fname.GetName() + _T(".png");
            settingsOffFilename = fname.GetName() + _T("-off.png");
            if (!platform::windows && resourceFilename.StartsWith(_T("lib")))
                resourceFilename.Remove(0, 3);
            if (!platform::windows && settingsOnFilename.StartsWith(_T("lib")))
                settingsOnFilename.Remove(0, 3);
            if (!platform::windows && settingsOffFilename.StartsWith(_T("lib")))
                settingsOffFilename.Remove(0, 3);
            resourceFilename = ConfigManager::LocateDataFile(resourceFilename, sdDataGlobal | sdDataUser);
            settingsOnFilename = ConfigManager::LocateDataFile(_T("images/settings/") + settingsOnFilename, sdDataGlobal | sdDataUser);
            settingsOffFilename = ConfigManager::LocateDataFile(_T("images/settings/") + settingsOffFilename, sdDataGlobal | sdDataUser);

            ReadExtraFilesFromManifestFile(resourceFilename, extrafiles);
            for (size_t n = 0; n < extrafiles.GetCount(); ++n)
            {
                extrafiles[n] = ConfigManager::LocateDataFile(extrafiles[n], sdDataGlobal | sdDataUser);
            }
            break;
        }
    }

    if (wxFileExists(pluginFilename) && !wxFile::Access(pluginFilename, wxFile::write))
    {
        // no write-access; abort
        cbMessageBox(_("You don't have the needed privileges to uninstall this plugin.\n"
                        "Ask your administrator to uninstall this plugin for you..."),
                        _("Warning"), wxICON_WARNING);
        return false;
    }

//    Manager::Get()->GetLogManager()->DebugLog(F(_T("UninstallPlugin:")));
//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Plugin filename: ") + pluginFilename));
//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Plugin resources: ") + resourceFilename));

    wxProgressDialog pd(wxString::Format(_("Uninstalling %s"), title.c_str()),
                        _T("A description wide enough for the dialog ;)"), 3);

    pd.Update(1, _("Detaching plugin"));
    DetachPlugin(plugin);
//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Plugin released")));

    pd.Update(2, _("Updating menus and toolbars"));
    CodeBlocksEvent event(cbEVT_PLUGIN_UNINSTALLED);
    event.SetPlugin(plugin);
    Manager::Get()->ProcessEvent(event);
//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Menus updated")));

    pd.Update(3, _("Unloading plugin"));
    UnloadPlugin(plugin);
//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Plugin unloaded")));

    if (!removeFiles)
        return true;

    // under linux, if the progress dialog is still visible and updated
    // causes a crash because it re-enters gtk_main_iteration() calling
    // eventually OnUpdateUI() in the config dialog, which in turn references
    // an invalid plugin...
//    pd.Update(4, _("Removing files"));

    if (!pluginFilename.IsEmpty())
    {
        if (wxRemoveFile(pluginFilename))
        {
//            Manager::Get()->GetLogManager()->DebugLog(F(_T("Plugin file removed")));
            if (!resourceFilename.IsEmpty())
            {
                if (!wxRemoveFile(resourceFilename))
                    Manager::Get()->GetLogManager()->LogWarning(_T("Failed to remove plugin resources: ") + resourceFilename);
            }
            if (!settingsOnFilename.IsEmpty() && wxFileExists(settingsOnFilename))
            {
                if (!wxRemoveFile(settingsOnFilename))
                    Manager::Get()->GetLogManager()->LogWarning(_T("Failed to remove icon for \"Settings\" dialog: ") + settingsOnFilename);
            }
            if (!settingsOffFilename.IsEmpty() && wxFileExists(settingsOffFilename))
            {
                if (!wxRemoveFile(settingsOffFilename))
                    Manager::Get()->GetLogManager()->LogWarning(_T("Failed to remove icon for \"Settings\" dialog: ") + settingsOffFilename);
            }
            for (size_t i = 0; i < extrafiles.GetCount(); ++i)
            {
                if (!extrafiles[i].IsEmpty() && wxFileExists(extrafiles[i]))
                {
                    if (!wxRemoveFile(extrafiles[i]))
                        Manager::Get()->GetLogManager()->LogWarning(_T("Failed to remove extra file: ") + extrafiles[i]);
                }
            }
            return true;
        }
        else
        {
            Manager::Get()->GetLogManager()->LogWarning(_T("Failed to remove plugin file: ") + pluginFilename);
            cbMessageBox(_("Plugin could not be completely uninstalled because its files could not be removed.\n\n"
                            "This can happen if the plugin's file is in-use like, for "
                            "example, when the same plugin file provides more than one "
                            "plugin.\n"
                            "In this case either uninstall all other plugins "
                            "which are provided by the same file, or remove it yourself "
                            "(manually) when you shut down Code::Blocks.\n"
                            "The files that could not be deleted are:\n\n") +
                            pluginFilename + _T('\n') +
                            resourceFilename + _T('\n') +
                            settingsOnFilename + _T('\n') +
                            settingsOffFilename,
                            _("Warning"), wxICON_WARNING);
            return false;
        }
    }
    return false;
}
wxArrayString DirectCommands::GetCompileFileCommand(ProjectBuildTarget* target, ProjectFile* pf) const
{
    wxArrayString ret;
    wxArrayString ret_generated;

    // is it compilable?
    if (!pf || !pf->compile)
        return ret;

    if (pf->compilerVar.IsEmpty())
    {
        Manager::Get()->GetLogManager()->DebugLog(_("Cannot resolve compiler var for project file."));
        return ret;
    }

    Compiler* compiler = target
                       ? CompilerFactory::GetCompiler(target->GetCompilerID())
                       : m_pCompiler;
    if (!compiler)
    {
        Manager::Get()->GetLogManager()->DebugLog(_("Can't access compiler for file."));
        return ret;
    }

    const pfDetails& pfd = pf->GetFileDetails(target);
    wxString object      = (compiler->GetSwitches().UseFlatObjects)
                         ? pfd.object_file_flat : pfd.object_file;
    wxString object_dir  = (compiler->GetSwitches().UseFlatObjects)
                         ? pfd.object_dir_flat_native : pfd.object_dir_native;
    // create output dir
    if (!object_dir.IsEmpty() && !CreateDirRecursively(object_dir, 0755))
        Manager::Get()->GetLogManager()->DebugLog(_("Can't create object output directory:\n") + object_dir);

    // lookup file's type
    const FileType ft = FileTypeOf(pf->relativeFilename);

    bool is_resource = ft == ftResource;
    bool is_header   = ft == ftHeader;

    // allowed resources under all platforms: makes sense when cross-compiling for
    // windows under linux.
    // and anyway, if the user is dumb enough to try to compile resources without
    // having a resource compiler, (s)he deserves the upcoming build error ;)

    wxString compiler_cmd;
    if (!is_header || compiler->GetSwitches().supportsPCH)
    {
        const CompilerTool* tool = compiler->GetCompilerTool(is_resource ? ctCompileResourceCmd : ctCompileObjectCmd, pf->file.GetExt());

        // does it generate other files to compile?
        for (size_t i = 0; i < pf->generatedFiles.size(); ++i)
            AppendArray(GetCompileFileCommand(target, pf->generatedFiles[i]), ret_generated); // recurse

        pfCustomBuild& pcfb = pf->customBuild[compiler->GetID()];
        if (pcfb.useCustomBuildCommand)
            compiler_cmd = pcfb.buildCommand;
        else if (tool)
            compiler_cmd = tool->command;
        else
            compiler_cmd = wxEmptyString;

        wxString source_file;
        if (compiler->GetSwitches().UseFullSourcePaths)
            source_file = UnixFilename(pfd.source_file_absolute_native);
        else
            source_file = pfd.source_file;

#ifdef command_line_generation
        Manager::Get()->GetLogManager()->DebugLog(F(_T("GetCompileFileCommand[1]: compiler_cmd='%s', source_file='%s', object='%s', object_dir='%s'."),
                                                    compiler_cmd.wx_str(), source_file.wx_str(), object.wx_str(), object_dir.wx_str()));
#endif

        // for resource files, use short from if path because if windres bug with spaces-in-paths
        if (is_resource && compiler->GetSwitches().UseFullSourcePaths)
            source_file = pf->file.GetShortPath();

        QuoteStringIfNeeded(source_file);

#ifdef command_line_generation
        Manager::Get()->GetLogManager()->DebugLog(F(_T("GetCompileFileCommand[2]: source_file='%s'."),
                                                    source_file.wx_str()));
#endif

        m_pGenerator->GenerateCommandLine(compiler_cmd,
                                          target,
                                          pf,
                                          source_file,
                                          object,
                                          pfd.object_file_flat,
                                          pfd.dep_file);
    }

    if (!is_header && compiler_cmd.IsEmpty())
    {
        ret.Add(COMPILER_SIMPLE_LOG + _("Skipping file (no compiler program set): ") + pfd.source_file_native );
        return ret;
    }

    switch (compiler->GetSwitches().logging)
    {
        case clogFull:
            ret.Add(COMPILER_SIMPLE_LOG + compiler_cmd);
            break;

        case clogSimple:
            if (is_header)
                ret.Add(COMPILER_SIMPLE_LOG + _("Pre-compiling header: ") + pfd.source_file_native );
            else
                ret.Add(COMPILER_SIMPLE_LOG + _("Compiling: ") + pfd.source_file_native );
            break;

        case clogNone: // fall-through
        default:
            break;
    }

    AddCommandsToArray(compiler_cmd, ret);

    if (is_header)
        ret.Add(COMPILER_WAIT);

    if (ret_generated.GetCount())
    {
        // not only append commands for (any) generated files to be compiled
        // but also insert a "pause" to allow this file to generate its files first
        if (!is_header) // if is_header, the "pause" has already been added
            ret.Add(COMPILER_WAIT);
        AppendArray(ret_generated, ret);
    }

    // if it's a PCH, delete the previously generated PCH to avoid problems
    // (it 'll be recreated anyway)
    if ( (ft == ftHeader) && pf->compile )
    {
        wxString object_abs = (compiler->GetSwitches().UseFlatObjects)
                            ? pfd.object_file_flat_absolute_native
                            : pfd.object_file_absolute_native;

        if ( wxFileExists(object_abs) && !wxRemoveFile(object_abs) )
            Manager::Get()->GetLogManager()->DebugLog(_("Cannot remove old PCH file:\n") + object_abs);
    }

    return ret;
}
Esempio n. 5
0
	virtual SetP importSet(const String& filename) {
		wxString set_name = filename;
		set_name.Replace(_("\\"),_("/"));
		// Strip "/set" from the end, newer wx versions have a function for this:
		//   filename.EndsWith(_("/set"), &set_name);
		if (set_name.size() > 4 && set_name.substr(set_name.size()-4) == _("/set")) {
			set_name.resize(set_name.size()-4);
		}
		// Or even worse: the file open dialog may append "/set.mse-set"
		if (set_name.size() > 20 && set_name.substr(set_name.size()-20) == _(".mse-set/set.mse-set") && !wxFileExists(set_name)) {
			set_name.resize(set_name.size()-12);
		}
		// Open the set
		SetP set(new Set);
		set->open(set_name);
		settings.addRecentFile(set_name);
		return set;
	}
Esempio n. 6
0
void MapEditorWindow::buildNodes(Archive* wad)
{
	NodeBuilders::builder_t builder;
	string command;
	string options;

	// Save wad to disk
	string filename = appPath("sladetemp.wad", DIR_TEMP);
	wad->save(filename);

	// Get current nodebuilder
	builder = NodeBuilders::getBuilder(nodebuilder_id);
	command = builder.command;
	options = nodebuilder_options;

	// Switch to ZDBSP if UDMF
	if (mdesc_current.format == MAP_UDMF && nodebuilder_id != "zdbsp")
	{
		wxMessageBox("Nodebuilder switched to ZDBSP for UDMF format", "Save Map", wxICON_INFORMATION);
		builder = NodeBuilders::getBuilder("zdbsp");
		command = builder.command;
	}

	// Check for undefined path
	if (!wxFileExists(builder.path) && !nb_warned)
	{
		// Open nodebuilder preferences
		PreferencesDialog::openPreferences(this, "Node Builders");

		// Get new builder if one was selected
		builder = NodeBuilders::getBuilder(nodebuilder_id);
		command = builder.command;

		// Check again
		if (!wxFileExists(builder.path))
		{
			wxMessageBox("No valid Node Builder is currently configured, nodes will not be built!", "Warning", wxICON_WARNING);
			nb_warned = true;
		}
	}

	// Build command line
	command.Replace("$f", S_FMT("\"%s\"", filename));
	command.Replace("$o", wxString(options));

	// Run nodebuilder
	if (wxFileExists(builder.path))
	{
		wxArrayString out;
		wxLogMessage("execute \"%s %s\"", builder.path, command);
		theApp->SetTopWindow(this);
		wxExecute(S_FMT("\"%s\" %s", builder.path, command), out, wxEXEC_HIDE_CONSOLE);
		theApp->SetTopWindow(theMainWindow);
		wxLogMessage("Nodebuilder output:");
		for (unsigned a = 0; a < out.size(); a++)
			wxLogMessage(out[a]);

		// Re-load wad
		wad->close();
		wad->open(filename);
	}
	else if (nb_warned)
		wxLogMessage("Nodebuilder path not set up, no nodes were built");
}
Esempio n. 7
0
/* DirArchive::save
 * Saves any changes to the directory to the file system
 *******************************************************************/
bool DirArchive::save(string filename)
{
	// Get flat entry list
	vector<ArchiveEntry*> entries;
	getEntryTreeAsList(entries);

	// Get entry path list
	vector<string> entry_paths;
	for (unsigned a = 0; a < entries.size(); a++)
	{
		entry_paths.push_back(this->filename + entries[a]->getPath(true));
		if (separator != "/") entry_paths.back().Replace("/", separator);
	}

	// Get current directory structure
	long time = theApp->runTimer();
	vector<string> files, dirs;
	DirArchiveTraverser traverser(files, dirs);
	wxDir dir(this->filename);
	dir.Traverse(traverser, "", wxDIR_FILES|wxDIR_DIRS);
	//wxDir::GetAllFiles(this->filename, &files, wxEmptyString, wxDIR_FILES|wxDIR_DIRS);
	LOG_MESSAGE(2, "GetAllFiles took %lums", theApp->runTimer() - time);

	// Check for any files to remove
	time = theApp->runTimer();
	for (unsigned a = 0; a < removed_files.size(); a++)
	{
		if (wxFileExists(removed_files[a]))
		{
			LOG_MESSAGE(2, "Removing file %s", removed_files[a]);
			wxRemoveFile(removed_files[a]);
		}
	}

	// Check for any directories to remove
	for (int a = dirs.size() - 1; a >= 0; a--)
	{
		// Check if dir path matches an existing dir
		bool found = false;
		for (unsigned e = 0; e < entry_paths.size(); e++)
		{
			if (dirs[a] == entry_paths[e])
			{
				found = true;
				break;
			}
		}

		// Dir on disk isn't part of the archive in memory
		// (Note that this will fail if there are any untracked files in the
		// directory)
		if (!found && wxRmdir(dirs[a]))
			LOG_MESSAGE(2, "Removing directory %s", dirs[a]);
	}
	LOG_MESSAGE(2, "Remove check took %lums", theApp->runTimer() - time);

	// Go through entries
	vector<string> files_written;
	for (unsigned a = 0; a < entries.size(); a++)
	{
		// Check for folder
		string path = entry_paths[a];
		if (entries[a]->getType() == EntryType::folderType())
		{
			// Create if needed
			if (!wxDirExists(path))
				wxMkdir(path);

			// Set unmodified
			entries[a]->exProp("filePath") = path;
			entries[a]->setState(0);

			continue;
		}

		// Check if entry needs to be (re)written
		if (entries[a]->getState() == 0 && path == entries[a]->exProp("filePath").getStringValue())
			continue;

		// Write entry to file
		if (!entries[a]->exportFile(path))
		{
			LOG_MESSAGE(1, "Unable to save entry %s: %s", entries[a]->getName(), Global::error);
		}
		else
			files_written.push_back(path);

		// Set unmodified
		entries[a]->setState(0);
		entries[a]->exProp("filePath") = path;
		file_modification_times[entries[a]] = wxFileModificationTime(path);
	}

	removed_files.clear();
	setModified(false);

	return true;
}
Esempio n. 8
0
void CGameListCtrl::CompressSelection(bool _compress)
{
	wxString dirHome;
	wxGetHomeDir(&dirHome);

	wxDirDialog browseDialog(this, _("Browse for output directory"), dirHome,
			wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST);
	if (browseDialog.ShowModal() != wxID_OK)
		return;

	bool all_good = true;

	{
	wxProgressDialog progressDialog(
		_compress ? _("Compressing ISO") : _("Decompressing ISO"),
		_("Working..."),
		1000,
		this,
		wxPD_APP_MODAL |
		wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
		wxPD_SMOOTH
		);

	m_currentItem = 0;
	m_numberItem = GetSelectedItemCount();
	for (u32 i=0; i < m_numberItem; i++)
	{
		const GameListItem *iso = GetSelectedISO();

			if (!iso->IsCompressed() && _compress)
			{
				std::string FileName, FileExt;
				SplitPath(iso->GetFileName(), NULL, &FileName, &FileExt);
				m_currentFilename = FileName;
				FileName.append(".gcz");

				std::string OutputFileName;
				BuildCompleteFilename(OutputFileName,
						WxStrToStr(browseDialog.GetPath()),
						FileName);

				if (wxFileExists(StrToWxStr(OutputFileName)) &&
						wxMessageBox(
							wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"),
								StrToWxStr(OutputFileName)), 
							_("Confirm File Overwrite"),
							wxYES_NO) == wxNO)
					continue;

				all_good &= DiscIO::CompressFileToBlob(iso->GetFileName().c_str(),
						OutputFileName.c_str(),
						(iso->GetPlatform() == GameListItem::WII_DISC) ? 1 : 0,
						16384, &MultiCompressCB, &progressDialog);
			}
			else if (iso->IsCompressed() && !_compress)
			{
				std::string FileName, FileExt;
				SplitPath(iso->GetFileName(), NULL, &FileName, &FileExt);
				m_currentFilename = FileName;
				if (iso->GetPlatform() == GameListItem::WII_DISC)
					FileName.append(".iso");
				else
					FileName.append(".gcm");

				std::string OutputFileName;
				BuildCompleteFilename(OutputFileName,
						WxStrToStr(browseDialog.GetPath()),
						FileName);

				if (wxFileExists(StrToWxStr(OutputFileName)) &&
						wxMessageBox(
							wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"),
								StrToWxStr(OutputFileName)), 
							_("Confirm File Overwrite"),
							wxYES_NO) == wxNO)
					continue;

				all_good &= DiscIO::DecompressBlobToFile(iso->GetFileName().c_str(),
						OutputFileName.c_str(), &MultiCompressCB, &progressDialog);
			}
			m_currentItem++;
	}
	}

	if (!all_good)
		wxMessageBox(_("Dolphin was unable to complete the requested action."));

	Update();
}
Esempio n. 9
0
void CGameListCtrl::OnCompressGCM(wxCommandEvent& WXUNUSED (event))
{
	const GameListItem *iso = GetSelectedISO();
	if (!iso)
		return;

	wxString path;

	std::string FileName, FilePath, FileExtension;
	SplitPath(iso->GetFileName(), &FilePath, &FileName, &FileExtension);

	do
	{
		if (iso->IsCompressed())
		{
			wxString FileType;
			if (iso->GetPlatform() == GameListItem::WII_DISC)
				FileType = _("All Wii ISO files (iso)") + wxString(wxT("|*.iso"));
			else
				FileType = _("All Gamecube GCM files (gcm)") + wxString(wxT("|*.gcm"));

			path = wxFileSelector(
					_("Save decompressed GCM/ISO"),
					StrToWxStr(FilePath),
					StrToWxStr(FileName) + FileType.After('*'),
					wxEmptyString,
					FileType + wxT("|") + wxGetTranslation(wxALL_FILES),
					wxFD_SAVE,
					this);
		}
		else
		{
			path = wxFileSelector(
					_("Save compressed GCM/ISO"),
					StrToWxStr(FilePath),
					StrToWxStr(FileName) + _T(".gcz"),
					wxEmptyString,
					_("All compressed GC/Wii ISO files (gcz)") + 
						wxString::Format(wxT("|*.gcz|%s"), wxGetTranslation(wxALL_FILES)),
					wxFD_SAVE,
					this);
		}
		if (!path)
			return;
	} while (wxFileExists(path) &&
			wxMessageBox(
				wxString::Format(_("The file %s already exists.\nDo you wish to replace it?"), path.c_str()), 
				_("Confirm File Overwrite"),
				wxYES_NO) == wxNO);

	bool all_good = false;

	{
	wxProgressDialog dialog(
		iso->IsCompressed() ? _("Decompressing ISO") : _("Compressing ISO"),
		_("Working..."),
		1000,
		this,
		wxPD_APP_MODAL |
		wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME |
		wxPD_SMOOTH
		);


	if (iso->IsCompressed())
		all_good = DiscIO::DecompressBlobToFile(iso->GetFileName().c_str(),
				path.char_str(), &CompressCB, &dialog);
	else
		all_good = DiscIO::CompressFileToBlob(iso->GetFileName().c_str(),
				path.char_str(),
				(iso->GetPlatform() == GameListItem::WII_DISC) ? 1 : 0,
				16384, &CompressCB, &dialog);
	}

	if (!all_good)
		wxMessageBox(_("Dolphin was unable to complete the requested action."));

	Update();
}
Esempio n. 10
0
bool GollyApp::OnInit()
{
   SetAppName(_("Golly"));    // for use in Warning/Fatal dialogs

   // create a stopwatch so we can use Time() to get elapsed millisecs
   stopwatch = new wxStopWatch();
   
   // set variable seed for later rand() calls
   srand(time(0));

   #if defined(__WXMAC__) && !wxCHECK_VERSION(2,7,2)
      // prevent rectangle animation when windows open/close
      wxSystemOptions::SetOption(wxMAC_WINDOW_PLAIN_TRANSITION, 1);
      // prevent position problem in wxTextCtrl with wxTE_DONTWRAP style
      // (but doesn't fix problem with I-beam cursor over scroll bars)
      wxSystemOptions::SetOption(wxMAC_TEXTCONTROL_USE_MLTE, 1);
   #endif

   // get current working directory before calling SetAppDirectory
   wxString initdir = wxFileName::GetCwd();
   if (initdir.Last() != wxFILE_SEP_PATH) initdir += wxFILE_SEP_PATH;

   // make sure current working directory contains application otherwise
   // we can't open Help files
   SetAppDirectory( wxString(argv[0]).mb_str(wxConvLocal) );

   // now set global gollydir for use in GetPrefs and elsewhere
   gollydir = wxFileName::GetCwd();
   if (gollydir.Last() != wxFILE_SEP_PATH) gollydir += wxFILE_SEP_PATH;
   
   // let non-wx modules call Fatal, Warning, BeginProgress, etc
   lifeerrors::seterrorhandler(&wxerrhandler);

   // allow .html files to include common graphic formats,
   // and .icons files to be in any of these formats;
   // note that wxBMPHandler is always installed, so it needs not be added,
   // and we can assume that if HAVE_WX_BMP_HANDLER is not defined, then
   // the handlers have not been auto-detected (and we just install them all).
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_GIF_HANDLER)
   wxImage::AddHandler(new wxGIFHandler);
#endif
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_PNG_HANDLER)
   wxImage::AddHandler(new wxPNGHandler);
#endif
#if !defined(HAVE_WX_BMP_HANDLER) || defined(HAVE_WX_TIFF_HANDLER)
   wxImage::AddHandler(new wxTIFFHandler);
#endif

   // wxInternetFSHandler is needed to allow downloading files
   wxFileSystem::AddHandler(new wxInternetFSHandler);
   wxFileSystem::AddHandler(new wxZipFSHandler);

   // get main window location and other user preferences
   GetPrefs();
   
   // create main window (also initializes viewptr, bigview, statusptr)
   mainptr = new MainFrame();
   if (mainptr == NULL) Fatal(_("Failed to create main window!"));
   
   // initialize some stuff before showing main window
   mainptr->SetRandomFillPercentage();
   mainptr->SetMinimumStepExponent();

   wxString banner = _("This is Golly version ");
   banner +=         _(STRINGIFY(VERSION)); 
   banner +=         _(".  Copyright 2012 The Golly Gang.");
   statusptr->SetMessage(banner);

   mainptr->NewPattern();

   // script/pattern files are stored in the pendingfiles array for later processing
   // in OnIdle; this avoids a crash in Win app if a script is run before showing
   // the main window, and also avoids event problems in Win app with a long-running
   // script (eg. user can't hit escape to abort script)
   const wxString START_PERL = wxT("golly-start.pl");
   const wxString START_PYTHON = wxT("golly-start.py");
   wxString startscript = gollydir + START_PERL;
   if (wxFileExists(startscript)) {
      mainptr->pendingfiles.Add(startscript);
   } else {
      // look in user-specific data directory
      startscript = datadir + START_PERL;
      if (wxFileExists(startscript)) {
         mainptr->pendingfiles.Add(startscript);
      }
   }
   startscript = gollydir + START_PYTHON;
   if (wxFileExists(startscript)) {
      mainptr->pendingfiles.Add(startscript);
   } else {
      // look in user-specific data directory
      startscript = datadir + START_PYTHON;
      if (wxFileExists(startscript)) {
         mainptr->pendingfiles.Add(startscript);
      }
   }
   
   // argc is > 1 if command line has one or more script/pattern files
   for (int n = 1; n < argc; n++) {
      wxFileName filename(argv[n]);
      // convert given path to a full path if not one already; this allows users
      // to do things like "../golly bricklayer.py" from within Scripts folder
      if (!filename.IsAbsolute()) filename = initdir + argv[n];
      mainptr->pendingfiles.Add(filename.GetFullPath());
   }

   // show main window
   if (maximize) mainptr->Maximize(true);
   mainptr->Show(true);
   SetTopWindow(mainptr);

   // true means call wxApp::OnRun() which will enter the main event loop;
   // false means exit immediately
   return true;
}
Esempio n. 11
0
bool wxFile::Exists(const wxString& name)
{
    return wxFileExists(name);
}
void PluginsConfigurationDlg::OnExport(wxCommandEvent& /*event*/)
{
    wxListCtrl* list = XRCCTRL(*this, "lstPlugins", wxListCtrl);
    if (list->GetSelectedItemCount() == 0)
        return;

    ConfigManager* cfg = Manager::Get()->GetConfigManager(_T("plugins_configuration"));
    wxDirDialog dd(this, _("Select directory to export plugin"), cfg->Read(_T("/last_export_path")), wxDD_NEW_DIR_BUTTON);
    if (dd.ShowModal() != wxID_OK)
        return;
    cfg->Write(_T("/last_export_path"), dd.GetPath());

    wxBusyCursor busy;
    wxProgressDialog pd(_("Exporting plugin(s)"),
                        _T("A description wide enough for the dialog ;)"),
                        list->GetSelectedItemCount(),
                        this,
                        wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT |
                        wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME);

    int count = 0;
    long sel = -1;
    bool skip = false;
    bool confirmed = false;
    wxString failure;
    wxArrayString files; // avoid exporting different plugins from the same file twice
    while (true)
    {
        sel = list->GetNextItem(sel, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
        if (sel == -1)
            break;

        const PluginElement* elem = (const PluginElement*)list->GetItemData(sel);
        if (!elem && !elem->plugin)
        {
            failure << list->GetItemText(sel) << _T('\n');
            continue;
        }

        // avoid duplicates
        if (files.Index(elem->fileName) != wxNOT_FOUND)
            continue;
        files.Add(elem->fileName);

        // normalize version
        wxString version = elem->info.version;
        version.Replace(_T("/"), _T("_"), true);
        version.Replace(_T("\\"), _T("_"), true);
        version.Replace(_T("?"), _T("_"), true);
        version.Replace(_T("*"), _T("_"), true);
        version.Replace(_T(">"), _T("_"), true);
        version.Replace(_T("<"), _T("_"), true);
        version.Replace(_T(" "), _T("_"), true);
        version.Replace(_T("\t"), _T("_"), true);
        version.Replace(_T("|"), _T("_"), true);

        wxFileName fname;
        fname.SetPath(dd.GetPath());
        fname.SetName(wxFileName(elem->fileName).GetName() + _T('-') + version);
        fname.SetExt(_T("cbplugin"));

        pd.Update(++count,
                    wxString::Format(_("Exporting \"%s\"..."), elem->info.title.c_str()),
                    &skip);
        if (skip)
            break;

        wxString filename = fname.GetFullPath();

        if (!confirmed && wxFileExists(filename))
        {
            AnnoyingDialog dlg(_("Confirmation"),
                                wxString::Format(_("%s already exists.\n"
                                "Are you sure you want to overwrite it?"), filename.c_str()),
                                wxART_QUESTION,
                                AnnoyingDialog::THREE_BUTTONS,
                                1,
                                true,
                                _("&Yes"), _("Yes to &all"), _("&No"));
            switch (dlg.ShowModal())
            {
                case 3:
                    continue;
                    break;

                case 2:
                    confirmed = true;
                    break;

                default:
                    break;
            }
        }

        if (!Manager::Get()->GetPluginManager()->ExportPlugin(elem->plugin, filename))
            failure << list->GetItemText(sel) << _T('\n');
    }

    if (!failure.IsEmpty())
        cbMessageBox(_("Failed exporting one or more plugins:\n\n") + failure, _("Warning"), wxICON_WARNING, this);
}
Esempio n. 13
0
void PCB_EDIT_FRAME::Process_Config( wxCommandEvent& event )
{
    int         id = event.GetId();
    wxFileName  fn;

    switch( id )
    {
    case ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG:
        m_show_layer_manager_tools = ! m_show_layer_manager_tools;
        m_auimgr.GetPane( wxT( "m_LayersManagerToolBar" ) ).Show( m_show_layer_manager_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_LAYERS_MANAGER_DIALOG,
                                m_show_layer_manager_tools ?
                                _("Hide &Layers Manager" ) : _("Show &Layers Manager" ));
        break;

    case ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR:
        m_show_microwave_tools  = ! m_show_microwave_tools;
        m_auimgr.GetPane( wxT( "m_microWaveToolBar" ) ).Show( m_show_microwave_tools );
        m_auimgr.Update();

        GetMenuBar()->SetLabel( ID_MENU_PCB_SHOW_HIDE_MUWAVE_TOOLBAR,
                                m_show_microwave_tools ?
                                _( "Hide Microwave Toolbar" ): _( "Show Microwave Toolbar" ));
        break;


    case ID_PCB_LAYERS_SETUP:
        if( InvokeLayerSetup( this, GetBoard() ) )
        {
            LAYER_ID cur_layer = GetActiveLayer();

            // If after showing the dialog the user has removed the active layer,
            // then select a new active layer (front copper layer).
            if( !GetBoard()->GetEnabledLayers()[ cur_layer ] )
                cur_layer = F_Cu;

            SetActiveLayer( cur_layer );

            OnModify();
            ReCreateLayerBox();
            ReFillLayerWidget();

            if( IsGalCanvasActive() )
                static_cast<PCB_DRAW_PANEL_GAL*>( GetGalCanvas() )->SyncLayersVisibility( GetBoard() );
        }
        break;

    case ID_PCB_LIB_WIZARD:
    case ID_PCB_LIB_TABLE_EDIT:
        {
            bool tableChanged = false;
            int r = 0;

            if( id == ID_PCB_LIB_TABLE_EDIT )
                r = InvokePcbLibTableEditor( this, &GFootprintTable, Prj().PcbFootprintLibs() );
            else
                r = InvokeFootprintWizard( this, &GFootprintTable, Prj().PcbFootprintLibs() );

            if( r & 1 )
            {
                try
                {
                    FILE_OUTPUTFORMATTER sf( FP_LIB_TABLE::GetGlobalTableFileName() );

                    GFootprintTable.Format( &sf, 0 );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving the global footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText.GetData() )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            // If no board file is defined, do not save the project specific library table.  It
            // is kept in memory and created in the path when the new board is saved.
            if( (r & 2) && !GetBoard()->GetFileName().IsEmpty() )
            {
                wxString    tblName   = Prj().FootprintLibTblName();

                try
                {
                    Prj().PcbFootprintLibs()->Save( tblName );
                    tableChanged = true;
                }
                catch( const IO_ERROR& ioe )
                {
                    wxString msg = wxString::Format( _(
                        "Error occurred saving project specific footprint library "
                        "table:\n\n%s" ),
                        GetChars( ioe.errorText )
                        );
                    wxMessageBox( msg, _( "File Save Error" ), wxOK | wxICON_ERROR );
                }
            }

            FOOTPRINT_VIEWER_FRAME* viewer;

            if( tableChanged && (viewer = (FOOTPRINT_VIEWER_FRAME*)Kiway().Player( FRAME_PCB_MODULE_VIEWER, false )) != NULL )
            {
                viewer->ReCreateLibraryList();
            }
        }
        break;

    case ID_PCB_3DSHAPELIB_WIZARD:
#ifdef BUILD_GITHUB_PLUGIN
        Invoke3DShapeLibsDownloaderWizard( this );
#endif
        break;

    case ID_PCB_MASK_CLEARANCE:
        {
            DIALOG_PADS_MASK_CLEARANCE dlg( this );

            if( dlg.ShowModal() == 1 && IsGalCanvasActive() )
            {
                for( MODULE* module = GetBoard()->m_Modules; module; module = module->Next() )
                    module->ViewUpdate();

                GetGalCanvas()->Refresh();
            }
        }
        break;

    case wxID_PREFERENCES:
        {
            DIALOG_GENERALOPTIONS dlg( this );
            dlg.ShowModal();
        }
        break;

    case ID_PCB_PAD_SETUP:
        InstallPadOptionsFrame( NULL );
        break;

    case ID_CONFIG_SAVE:
        SaveProjectSettings( true );
        break;

    case ID_CONFIG_READ:
        {
            fn = GetBoard()->GetFileName();
            fn.SetExt( ProjectFileExtension );

            wxFileDialog dlg( this, _( "Read Project File" ), fn.GetPath(),
                              fn.GetFullName(), ProjectFileWildcard,
                              wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

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

            if( !wxFileExists( dlg.GetPath() ) )
            {
                wxString msg = wxString::Format( _(
                        "File %s not found" ),
                        GetChars( dlg.GetPath() )
                        );
                DisplayError( this, msg );
                break;
            }

            wxString pro_file = dlg.GetPath();

            Prj().ConfigLoad( Kiface().KifaceSearch(), GROUP_PCB, GetProjectFileParameters(), pro_file );
        }
        break;

    // Hotkey IDs
    case ID_PREFERENCES_HOTKEY_EXPORT_CONFIG:
        ExportHotkeyConfigToFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_IMPORT_CONFIG:
        ImportHotkeyConfigFromFile( g_Board_Editor_Hokeys_Descr, wxT( "pcbnew" ) );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_EDITOR:
        InstallHotkeyFrame( this, g_Board_Editor_Hokeys_Descr );
        break;

    case ID_PREFERENCES_HOTKEY_SHOW_CURRENT_LIST:
        // Display current hotkey list for Pcbnew.
        DisplayHotkeyList( this, g_Board_Editor_Hokeys_Descr );
        break;

    // Macros IDs
    case ID_PREFRENCES_MACROS_SAVE:
        SaveMacros();
        break;

    case ID_PREFRENCES_MACROS_READ:
        ReadMacros();
        break;

    default:
        DisplayError( this, wxT( "PCB_EDIT_FRAME::Process_Config error" ) );
    }
}
Esempio n. 14
0
void PCB_EDIT_FRAME::ReadMacros()
{
    wxFileName fn;

    fn = GetBoard()->GetFileName();
    fn.SetExt( MacrosFileExtension );

    wxFileDialog dlg( this, _( "Read Macros File" ), fn.GetPath(),
                      fn.GetFullName(), MacrosFileWildcard,
                      wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR );

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

    if( !wxFileExists( dlg.GetPath() ) )
    {
        wxString msg;
        msg.Printf( _( "File %s not found" ), GetChars( dlg.GetPath() ) );
        DisplayError( this, msg );
        return;
    }

    wxXmlDocument xml;

    xml.SetFileEncoding( wxT( "UTF-8" ) );

    if( !xml.Load( dlg.GetFilename() ) )
            return;

    XNODE *macrosNode = (XNODE*) xml.GetRoot()->GetChildren();

    while( macrosNode )
    {
        int number = -1;

        if( macrosNode->GetName() == wxT( "macros" ) )
        {
            number = wxAtoi( macrosNode->GetAttribute( wxT( "number" ), wxT( "-1" ) ) );

            if( number >= 0  && number < 10 )
            {
                m_Macros[number].m_Record.clear();

                XNODE *hotkeyNode = macrosNode->GetChildren();

                while( hotkeyNode )
                {
                    if( hotkeyNode->GetName() == wxT( "hotkey" ) )
                    {
                        int x = wxAtoi( hotkeyNode->GetAttribute( wxT( "x" ), wxT( "0" ) ) );
                        int y = wxAtoi( hotkeyNode->GetAttribute( wxT( "y" ), wxT( "0" ) ) );
                        int hk = wxAtoi( hotkeyNode->GetAttribute( wxT( "hkcode" ), wxT( "0" ) ) );

                        MACROS_RECORD macros_record;
                        macros_record.m_HotkeyCode = hk;
                        macros_record.m_Position.x = x;
                        macros_record.m_Position.y = y;
                        m_Macros[number].m_Record.push_back( macros_record );
                    }

                    hotkeyNode = hotkeyNode->GetNext();
                }
            }
        }

        macrosNode = macrosNode->GetNext();
    }
}
Esempio n. 15
0
bool CAICHHashSet::LoadHashSet()
{
	if (m_eStatus != AICH_HASHSETCOMPLETE) {
		wxFAIL;
		return false;
	}
	if ( !m_pHashTree.m_bHashValid || m_pHashTree.m_nDataSize != m_pOwner->GetFileSize() || m_pHashTree.m_nDataSize == 0) {
		wxFAIL;
		return false;
	}
	wxString fullpath = theApp->ConfigDir + KNOWN2_MET_FILENAME;
	CFile file(fullpath, CFile::read);
	if (!file.IsOpened()) {
		if (wxFileExists(fullpath)) {
			wxString strError(wxT("Failed to load ") KNOWN2_MET_FILENAME wxT(" file"));
			AddDebugLogLineC(logSHAHashSet, strError);
		}
		return false;
	}

	try {
		uint8 header = file.ReadUInt8();
		if (header != KNOWN2_MET_VERSION) {
			AddDebugLogLineC(logSHAHashSet, wxT("Loading failed: Current file is not a met-file!"));
			return false;
		}

		CAICHHash CurrentHash;
		uint64 nExistingSize = file.GetLength();
		uint32 nHashCount;
		while (file.GetPosition() < nExistingSize) {
			CurrentHash.Read(&file);
			if (m_pHashTree.m_Hash == CurrentHash) {
				// found Hashset
				uint32 nExpectedCount =	(PARTSIZE/EMBLOCKSIZE + ((PARTSIZE % EMBLOCKSIZE != 0)? 1 : 0)) * (m_pHashTree.m_nDataSize/PARTSIZE);
				if (m_pHashTree.m_nDataSize % PARTSIZE != 0) {
					nExpectedCount += (m_pHashTree.m_nDataSize % PARTSIZE)/EMBLOCKSIZE + (((m_pHashTree.m_nDataSize % PARTSIZE) % EMBLOCKSIZE != 0)? 1 : 0);
				}
				nHashCount = file.ReadUInt32();
				if (nHashCount != nExpectedCount) {
					AddDebugLogLineC(logSHAHashSet, wxT("Failed to load HashSet: Available Hashs and expected hashcount differ!"));
					return false;
				}
				if (!m_pHashTree.LoadLowestLevelHashs(&file)) {
					AddDebugLogLineC(logSHAHashSet, wxT("Failed to load HashSet: LoadLowestLevelHashs failed!"));
					return false;
				}
				if (!ReCalculateHash(false)) {
					AddDebugLogLineC(logSHAHashSet, wxT("Failed to load HashSet: Calculating loaded hashs failed!"));
					return false;
				}
				if (CurrentHash != m_pHashTree.m_Hash) {
					AddDebugLogLineC(logSHAHashSet, wxT("Failed to load HashSet: Calculated Masterhash differs from given Masterhash - hashset corrupt!"));
					return false;
				}
				return true;
			}
			nHashCount = file.ReadUInt32();
			if (file.GetPosition() + nHashCount*HASHSIZE > nExistingSize) {
				AddDebugLogLineC(logSHAHashSet, wxT("Saving failed: File contains fewer entries than specified!"));
				return false;
			}
			// skip the rest of this hashset
			file.Seek(nHashCount*HASHSIZE, wxFromCurrent);
		}
		AddDebugLogLineC(logSHAHashSet, wxT("Failed to load HashSet: HashSet not found!"));
	} catch (const CSafeIOException& e) {
		AddDebugLogLineC(logSHAHashSet, wxT("IO error while loading AICH HashSet: ") + e.what());
	}

	return false;
}
Esempio n. 16
0
void* UpdateThread::Entry( )
{
  if ( m_bIsAutoUpdate )
  {
    m_frame->SetToolTip( _("Auto-Updating blocklist") );
  }
  else
  {
    m_frame->SetToolTip( _("Updating blocklist") );
    m_frame->AddToLog( _("Updating blocklist") );
  }

  //  1030
  //  http://homepage.ntlworld.com/tim.leonard1/pgupdate.htm?04-FEB-04
  wxString tmp = DownloadURL( wxT("homepage.ntlworld.com"), wxT("/tim.leonard1/pglistver.txt") );
//  wxTextInputStream( tmp );

  wxRegEx regex( wxT("([0-9]*)\r\n(.*)") );
  wxString  url;
  long      ver(-1);
  bool      bNeedReload;
  if ( regex.Matches(tmp) )
  {
    regex.GetMatch(tmp, 1).ToLong( &ver );
    url    = regex.GetMatch(tmp, 2); url.Trim();
  }

  bNeedReload = false;
  if ( ver == -1 )
  {
    if ( m_bIsAutoUpdate )
      ShowError( _("Unable to autoupdate!") );
    else
      ShowError( _("Unable to update!") );
  }
  else if ( !wxFileExists(wxGetPath(DATABASE_FILE)) || ver < DefaultConfig->GetDbVersion() )
  {
    if ( !m_bIsAutoUpdate )
      m_frame->AddToLog( _("New version detected... Download started...") );

    tmp = DownloadURL( wxT("homepage.ntlworld.com"), wxT("/tim.leonard1/guarding.p2p") );

    if ( !tmp.empty() )
    {
      wxFile fp( wxGetPath(DATABASE_FILE), wxFile::write );
      fp.Write( tmp.mb_str(), tmp.Length() );
      fp.Close();

      if ( !m_bIsAutoUpdate )
      {
        m_frame->AddToLog( _("Update saved... Reloading IP database...") );
      }
      bNeedReload = true;
    }
    else if ( m_bIsAutoUpdate )
    {
      bNeedReload = true;
    }
  }
  DefaultConfig->SetDbVersion( ver );

  if ( IPDatabase == NULL )
  {
    IPDatabase = new Database( m_frame );
    if ( !IPDatabase->IsOk() )
    {
      ShowError( _("Invalid database-file!") );
      m_frame->Destroy( );
      return NULL;
    }
    m_frame->AddToLog( wxString::Format( _("Successfully loaded %lu IPs from %lu profiles."), IPDatabase->AmountOfIPs(), IPDatabase->AmountOfRanges() ) );
  }
  else if ( bNeedReload )
  {
    IPDatabase->Reload();
    m_frame->AddToLog( wxString::Format( _("Successfully loaded %lu IPs from %lu profiles."), IPDatabase->AmountOfIPs(), IPDatabase->AmountOfRanges() ) );
  }
  else
  {
    m_frame->AddToLog( _("You already have the latest version!") );
  }

  m_frame->SetToolTip( VERSION );
  return NULL;
}
Esempio n. 17
0
void StyleDialog::OnStyleWebSummary ( wxCommandEvent& event )
{
	std::vector<ContextMatch> v;
	getAllMatches ( v );

	std::map<std::string, int, NoCaseCompare> matchMap;
	std::vector<ContextMatch>::iterator vectorIterator;
	for (
	    vectorIterator = v.begin();
	    vectorIterator != v.end();
	    ++vectorIterator )
	{
		if ( ( matchMap.find ( vectorIterator->match ) ) != matchMap.end() )
			++ ( matchMap[vectorIterator->match] );
		else
			matchMap[vectorIterator->match] = 1;
	}

	// temporary file should be in default temporary folder
	wxString tempNameWide = wxFileName::CreateTempFileName ( _T ( "" ) );
	if ( tempNameWide.empty() )
		return;
	tempNameWide.Replace ( _T ( ".tmp" ), _T ( "_summary.html" ), true );
	tempFiles.insert ( tempNameWide );
	std::string tempNameUtf8 = ( const char * ) tempNameWide.mb_str ( wxConvUTF8 );
	std::ofstream ofs ( tempNameUtf8.c_str() );
	if ( !ofs )
		return;
	ofs << XHTML_START;
	ofs << "<body><h2>";
	ofs << fileName.mb_str ( wxConvUTF8 );
	ofs << "</h2>";

	WrapExpat we;
	ofs << "<table><tr><th>Term</th><th>Frequency</th></tr>";
	std::map<std::string, int>::iterator mapIterator;
	int matchTotal = 0;

	for (
	    mapIterator = matchMap.begin();
	    mapIterator != matchMap.end();
	    ++mapIterator )
	{
		ofs << "<tr><td>";
		ofs << we.xmliseTextNode ( mapIterator->first );
		ofs << "</td><td>";

		// handle number of matches
		matchTotal += mapIterator->second;
		ofs << mapIterator->second;
		ofs << "</td></tr>";
	}
	ofs << "<tr><th>Total</th><th>";
	ofs << matchTotal;
	ofs << "</th></tr></table></body>";
	ofs << XHTML_END;

	ofs.close();

	// display file in browser
	if ( !wxFileExists ( tempNameWide ) )
		return;

	wxLaunchDefaultBrowser ( tempNameWide );
}
Esempio n. 18
0
AutoDetectResult CompilerG95::AutoDetectInstallationDir()
{
    // try to find MinGW in environment variable PATH first
    wxString pathValues;
    wxGetEnv(_T("PATH"), &pathValues);
    if (!pathValues.IsEmpty())
    {
        wxString sep = platform::windows ? _T(";") : _T(":");
        wxChar pathSep = platform::windows ? _T('\\') : _T('/');
        wxArrayString pathArray = GetArrayFromString(pathValues, sep);
        for (size_t i = 0; i < pathArray.GetCount(); ++i)
        {
            if (wxFileExists(pathArray[i] + pathSep + m_Programs.C))
            {
                if (pathArray[i].AfterLast(pathSep).IsSameAs(_T("bin")))
                {
                    m_MasterPath = pathArray[i].BeforeLast(pathSep);
                    return adrDetected;
                }
            }
        }
    }

    wxString sep = wxFileName::GetPathSeparator();
    if (platform::windows)
    {
        // look first if MinGW was installed with Code::Blocks (new in beta6)
        m_MasterPath = ConfigManager::GetExecutableFolder();
        if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.C))
            // if that didn't do it, look under C::B\MinGW, too (new in 08.02)
            m_MasterPath += sep + _T("MinGW");
        if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.C))
        {
            // no... search for MinGW installation dir
            wxString windir = wxGetOSDirectory();
            wxFileConfig ini(_T(""), _T(""), windir + _T("/MinGW.ini"), _T(""), wxCONFIG_USE_LOCAL_FILE | wxCONFIG_USE_NO_ESCAPE_CHARACTERS);
            m_MasterPath = ini.Read(_T("/InstallSettings/InstallPath"), _T("C:\\MinGW"));
            if (!wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.C))
            {
#ifdef __WXMSW__ // for wxRegKey
                // not found...
                // look for dev-cpp installation
                wxRegKey key; // defaults to HKCR
                key.SetName(_T("HKEY_LOCAL_MACHINE\\Software\\Dev-C++"));
                if (key.Exists() && key.Open(wxRegKey::Read))
                {
                    // found; read it
                    key.QueryValue(_T("Install_Dir"), m_MasterPath);
                }
                else
                {
                    // installed by inno-setup
                    // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Minimalist GNU for Windows 4.1_is1
                    wxString name;
                    long index;
                    key.SetName(_T("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"));
                    //key.SetName("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion");
                    bool ok = key.GetFirstKey(name, index);
                    while (ok && !name.StartsWith(_T("Minimalist GNU for Windows")))
                    {
                        ok = key.GetNextKey(name, index);
                    }
                    if (ok)
                    {
                        name = key.GetName() + _T("\\") + name;
                        key.SetName(name);
                        if (key.Exists() && key.Open(wxRegKey::Read))
                            key.QueryValue(_T("InstallLocation"), m_MasterPath);
                    }
                }
#endif
            }
        }
        else
            m_Programs.MAKE = _T("make.exe"); // we distribute "make" not "mingw32-make"
    }
    else
        m_MasterPath = _T("/usr");

    AutoDetectResult ret = wxFileExists(m_MasterPath + sep + _T("bin") + sep + m_Programs.C) ? adrDetected : adrGuessed;
    // don't add lib/include dirs. GCC knows where its files are located

    SetVersionString();
    return ret;
}
Esempio n. 19
0
MyFrame::MyFrame(wxFrame *frame, const wxChar *title, int x, int y, int w, int h)
    : wxFrame(frame, wxID_ANY, title, wxPoint(x, y), wxSize(w, h)),
    mpNestedLayout( NULL ),
    mpAboutBoxLayout( NULL ),

    mActiveLayoutNo( FIRST_LAYOUT ),
    mAutoSave( true ),
    mSavedAlready( false ),
    mpClntWindow( NULL ),

    mImageList( 16,16, false, 2 )
{
    int i;

    mpInternalFrm = (wxPanel*)this;

    mAboutBox.Create( this, wxID_ANY,  _T("About box in wxWidgets style..."),
                      wxDefaultPosition,
                      wxSize( 385,220),
                      wxDEFAULT_DIALOG_STYLE | wxTAB_TRAVERSAL );

    for( i = 0; i != MAX_LAYOUTS; ++i )
        mLayouts[i] = NULL;

    // image-list is one of the few objects which
    // currently cannot be serialized, create it first
    // and use it as initial reference (IR)

    wxBitmap bmp1,bmp2;

    if ( wxFileExists( wxString(wxT(BMP_DIR)) + wxT("folder_icon.bmp") ) )
        bmp1.LoadFile( wxString(wxT(BMP_DIR)) + wxT("folder_icon.bmp"), wxBITMAP_TYPE_BMP );

    if ( wxFileExists( wxString(wxT(BMP_DIR)) + wxT("class_icon1.bmp") ) )
        bmp2.LoadFile( wxString(wxT(BMP_DIR)) + wxT("class_icon1.bmp"), wxBITMAP_TYPE_BMP );

    mImageList.Add( bmp1 );
    mImageList.Add( bmp2 );

    InitAboutBox();

    // create multiple layouts

    mpNestedLayout = 0;

    mpClntWindow = CreateTxtCtrl(wxT("client window"));

    // Create all layouts
    for( i = 0; i != MAX_LAYOUTS; ++i )
    {
        CreateLayout( i );
    }
    // hide others
    for( i = SECOND_LAYOUT; i != MAX_LAYOUTS; ++i )
    {
        mLayouts[i]->HideBarWindows();
    }

    // activate first one
    mLayouts[FIRST_LAYOUT]->Activate();
    mActiveLayoutNo = FIRST_LAYOUT;
}
Esempio n. 20
0
bool wxFlybotDLL::LogFileExists()
{
    return wxFileExists(GetLogFilename());
}
Esempio n. 21
0
bool MyApp::MakeSplash()
{
	// First, load the original (template) splash image.
	int imageType = wxDetermineImageType(m_inputFilename);
	wxImage templateImage;
	if (imageType == -1 || !wxFileExists(m_inputFilename) ||
		!templateImage.LoadFile(m_inputFilename, imageType))
	{
		wxString msg;
		msg.Printf(wxT("Sorry, could not load template image %s"), (const wxChar*) m_inputFilename);
		wxLogMessage(msg);
		return FALSE;
	}

	wxString msg;
	msg.Printf(wxT("Creating new file %s from template file %s and text %s"),
		(const wxChar*) m_outputFilename, (const wxChar*) m_inputFilename, (const wxChar*) m_text);
	Log(msg);

    wxScreenDC screenDC;
	bool useScaling = m_antialias && (m_scaleFactor > 1);
	int pointSize;

#if !USE_SCALING
    useScaling = FALSE;
#endif

	if (useScaling)
		pointSize = m_scaleFactor*m_fontPointSize;
	else
		pointSize = m_fontPointSize;

	wxString faceName = m_fontFaceName;

    wxFont font(pointSize, wxDEFAULT, m_fontStyle, m_fontWeight, FALSE, faceName);
    screenDC.SetFont(font);

    int w, h, scaledW, scaledH;
    screenDC.GetTextExtent(m_text, & w, & h);

	if (useScaling)
	{
		wxFont font2(m_fontPointSize, wxDEFAULT, m_fontStyle, m_fontWeight, FALSE, faceName);
		screenDC.SetFont(font2);
		screenDC.GetTextExtent(m_text, & scaledW, & scaledH);
	}

    screenDC.SetFont(wxNullFont);

	wxBrush backgroundBrush(m_textBackgroundColour, wxSOLID);

    wxBitmap bitmap(w, h);
    wxMemoryDC memDC;
    memDC.SelectObject(bitmap);
    memDC.SetFont(font);
    memDC.SetBackgroundMode(wxTRANSPARENT);
    memDC.SetTextForeground(m_textForegroundColour);
    memDC.SetBackground(backgroundBrush);
    memDC.SetBrush(backgroundBrush);
    memDC.Clear();
    memDC.DrawText(m_text, 0, 0);
    memDC.SelectObject(wxNullBitmap);

    wxImage image = bitmap.ConvertToImage();
	if (m_antialias)
	{
		wxImage anti = wxAntiAlias(image);
		image = anti;
	}

	if (useScaling)
	{
		// Now create an image and rescale it down to the original point size
		image.Rescale(w/m_scaleFactor, h/m_scaleFactor);
	}

	image.SetMaskColour(m_textBackgroundColour.Red(), m_textBackgroundColour.Green(), m_textBackgroundColour.Blue());
    
	wxBitmap bitmap2(image);

	// Now draw the image into the template image

	wxBitmap templateBitmap(templateImage);
	wxMemoryDC memDCTemplate;
	memDCTemplate.SelectObject(templateBitmap);
	
	int x, y;
	if (m_centre)
	{
		y = m_textPosition.y; // Currently, always start at this position
		x = m_textPosition.x - (image.GetWidth() / 2);
	}
	else if (m_rightJustify)
	{
		y = m_textPosition.y; // Currently, always start at this position
		x = m_textPosition.x - (image.GetWidth());
	}
	else
	{
		y = m_textPosition.y; // Currently, always start at this position
		x = m_textPosition.x;
	}
	memDCTemplate.DrawBitmap(bitmap2, x, y, TRUE);
	memDCTemplate.SelectObject(wxNullBitmap);

	wxImage completeImage = templateBitmap.ConvertToImage();

	int saveImageType = wxDetermineImageType(m_outputFilename);
	if (saveImageType == -1)
	{
		wxLogMessage(wxT("Sorry, unknown output image file type."));
		return FALSE;
	}

	((MyFrame*) GetTopWindow())->m_viewerWindow->SetBitmap(templateBitmap);

	// TODO: get the depth from the original image, and set for this image.
	// May have to do explicit image reduction for this to work.

	if (!completeImage.SaveFile(m_outputFilename, saveImageType))
	{
		wxString msg;
		msg.Printf(wxT("Sorry, could not save image to %s"), (const wxChar*) m_outputFilename);
		wxLogMessage(msg);
		return FALSE;
	}
#if 0
    if (wxTheClipboard->Open())
    {
        wxTheClipboard->Clear();
        wxTheClipboard->SetData(new wxBitmapDataObject(bitmap2));
        wxTheClipboard->Close();
    }
#endif
    return TRUE;
}
Esempio n. 22
0
DatabaseDlg::DatabaseDlg(wxWindow* frame, wxWindow* parent)
: wxPanel(parent, wxID_ANY,
wxPoint(500, 150), wxSize(440, 700),
0, "DatabaseDlg"),
m_frame(parent),
m_view(0)
{
	SetEvtHandlerEnabled(false);
	Freeze();

	wxBoxSizer *group1 = new wxBoxSizer(wxHORIZONTAL);
	m_url_text = new DBSearcher(parent, this, ID_SearchTextCtrl, wxT("Search"),
		wxDefaultPosition, wxSize(300, 23), wxTE_PROCESS_ENTER);
	m_download_btn = new wxButton(this, ID_DownloadBtn, wxT("Search"),
		wxDefaultPosition, wxSize(70, 23));
	group1->Add(5, 5);
	group1->Add(m_url_text, 1, wxEXPAND);
	group1->Add(5, 5);
	group1->Add(m_download_btn, 0, wxALIGN_CENTER);

	wxBoxSizer *group_g = new wxBoxSizer(wxHORIZONTAL);
	m_sch_gauge = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(300, 10));
	group_g->Add(5, 10);
	group_g->Add(m_sch_gauge, 1, wxEXPAND);
	group_g->Add(5, 10);
	
	//list
	m_dbtree = new DBTreeCtrl(frame, this, wxID_ANY);
	m_searchResult = new DBTreeCtrl(frame, this, wxID_ANY);

    wxString expath = wxStandardPaths::Get().GetExecutablePath();
    expath = expath.BeforeLast(GETSLASH(),NULL);
#ifdef _WIN32
    wxString dft = expath + "\\catalog_list.set";
	if (!wxFileExists(dft))
		dft = wxStandardPaths::Get().GetUserConfigDir() + "\\catalog_list.set";
#else
    wxString dft = expath + "/../Resources/" + "catalog_list.set";
#endif
    wxFileInputStream is(dft);
	if (is.IsOk())
	{
		wxTextInputStream tis(is);
		wxString str;

		while (!is.Eof())
		{
			wxString sline = tis.ReadLine();
			m_dbtree->LoadDatabase(sline);
		}
	}

	wxBoxSizer *group2 = new wxBoxSizer(wxHORIZONTAL);
	m_db_text = new DBSearcher(parent, this, ID_DBTextCtrl, wxT("URL or Path"),
		wxDefaultPosition, wxSize(330, 23), wxTE_PROCESS_ENTER);
	m_browse_btn = new wxButton(this, ID_BrowseBtn, wxT("Browse..."),
		wxDefaultPosition, wxSize(90, 23));
	group2->Add(5, 5);
	group2->Add(m_db_text, 1, wxEXPAND);
	group2->Add(5, 5);
	group2->Add(m_browse_btn, 0, wxALIGN_CENTER);
	group2->Add(5, 5);

	wxBoxSizer *group3 = new wxBoxSizer(wxHORIZONTAL);
	m_add_btn = new wxButton(this, ID_AddDBBtn, wxT("Add"),
		wxDefaultPosition, wxSize(90, 28));
	group3->AddStretchSpacer(1);
	group3->Add(5, 5);
	group3->Add(m_add_btn, 0, wxALIGN_CENTER);
	group3->Add(5, 5);

	//all controls
	wxBoxSizer *sizerV = new wxBoxSizer(wxVERTICAL);
	sizerV->Add(10, 10);
	sizerV->Add(group1, 0, wxEXPAND);
	sizerV->Add(10, 5);
	sizerV->Add(group_g, 0, wxEXPAND);
	sizerV->Add(10, 10);
	sizerV->Add(m_dbtree, 1, wxEXPAND);
	sizerV->Add(m_searchResult, 1, wxEXPAND);
	sizerV->Add(10, 20);
	sizerV->Add(group2, 0, wxEXPAND);
	sizerV->Add(10, 5);
	sizerV->Add(group3, 0, wxEXPAND);
	m_searchResult->Hide();
	m_sch_gauge->Hide();
	
	SetSizer(sizerV);
	Layout();

	m_thread = NULL;
	m_th_del = NULL;

	Thaw();
	SetEvtHandlerEnabled(true);
}
Esempio n. 23
0
/* Save modules in a library:
 * param aNewModulesOnly:
 *              true : save modules not already existing in this lib
 *              false: save all modules
 */
void PCB_EDIT_FRAME::ArchiveModulesOnBoard( const wxString& aLibName, bool aNewModulesOnly )
{
    wxString fileName = aLibName;
    wxString path;

    if( GetBoard()->m_Modules == NULL )
    {
        DisplayInfoMessage( this, FMT_NO_MODULES );
        return;
    }

    path = wxGetApp().ReturnLastVisitedLibraryPath();

    if( !aLibName )
    {
        wxFileDialog dlg( this, FMT_LIBRARY, path,
                          wxEmptyString,
                          wxGetTranslation( LegacyFootprintLibPathWildcard ),
                          wxFD_SAVE );

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

        fileName = dlg.GetPath();
    }

    wxFileName fn( fileName );
    wxGetApp().SaveLastVisitedLibraryPath( fn.GetPath() );
    bool       lib_exists = wxFileExists( fileName );

    if( !aNewModulesOnly && lib_exists )
    {
        wxString msg = wxString::Format( FMT_OK_OVERWRITE, GetChars( fileName ) );

        if( !IsOK( this, msg ) )
            return;
    }

    m_canvas->SetAbortRequest( false );

    try
    {
        PLUGIN::RELEASER pi( IO_MGR::PluginFind( IO_MGR::LEGACY ) );

        // Delete old library if we're replacing it entirely.
        if( lib_exists && !aNewModulesOnly )
        {
            pi->FootprintLibDelete( fileName );
            lib_exists = false;
        }

        if( !lib_exists )
        {
            pi->FootprintLibCreate( fileName );
        }

        if( !aNewModulesOnly )
        {
            for( MODULE* m = GetBoard()->m_Modules;  m;  m = m->Next() )
            {
                pi->FootprintSave( fileName, m );
            }
        }
        else
        {
            for( MODULE* m = GetBoard()->m_Modules;  m;  m = m->Next() )
            {
                if( !Save_Module_In_Library( fileName, m, false, false ) )
                    break;

                // Check for request to stop backup (ESCAPE key actuated)
                if( m_canvas->GetAbortRequest() )
                    break;
            }
        }
    }
    catch( IO_ERROR ioe )
    {
        DisplayError( this, ioe.errorText );
        return;
    }
}
Esempio n. 24
0
bool MoveDirWithFilebackupRename(wxString from, wxString to, bool backup, bool silent)
{
	// first make sure that the source dir exists
	if (!wxDir::Exists(from)) {
		ErrorMsgBox(from + _T(" does not exist.  Can not copy directory."), silent);
		return false;
	}

	if (from == to) {
		ErrorMsgBox(_T("Cannot copy: source == destination: ") + from, silent);
		return false;
	}

	if (from.empty() || to.empty()) {
		ErrorMsgBox(_T("Cannot copy empty directory"), silent);
		return false;
	}

	SafeMkdir(to);

	wxString sep = wxFileName::GetPathSeparator();

	wxDir dir(from);
	wxString filename;
	if (!dir.GetFirst(&filename)) {
		return false;
	}

	// append a slash if there is not one (for easier parsing)
	// because who knows what people will pass to the function.
	if (!to.EndsWith(sep)) {
		to += sep;
	}
	// for both dirs
	if (!from.EndsWith(sep)) {
		from += sep;
	}

	do {
		const wxString srcfile = from + filename;
		const wxString dstfile = to + filename;
		if (wxDirExists(srcfile)) {					      //check if srcfile is a directory
			MoveDirWithFilebackupRename(srcfile, dstfile, false, silent); //no backup in subdirs
		} else {
			//if files exists move it to backup, this way we can use this func on windows to replace 'active' files

			if (backup && wxFileExists(dstfile)) {
				const wxString backupfile = dstfile + _T(".old");
				if (!MoveFile(dstfile, backupfile)) {
					ErrorMsgBox(wxString::Format(_T("could not rename %s to %s. copydir aborted"), dstfile.c_str(), backupfile.c_str()), silent);
					return false;
				}
			}
			//do the actual copy
			if (!wxCopyFile(srcfile, dstfile, true)) {
				ErrorMsgBox(wxString::Format(_T("could not copy %s to %s, copydir aborted"), srcfile, dstfile), silent);
				return false;
			}
		}
	} while (dir.GetNext(&filename));
	return true;
}
void GADAPI::ExportToDicomDirCommand::Execute()
{
        if (!NotificarProgreso(0.0, _Std("Exporting files...")) )
                return;

        std::string pathOfDicomDir;
        {
                std::ostringstream ostr;
                ostr << m_pExportacionParams->m_destinationPath;
                ostr << (char)wxFileName::GetPathSeparator();
                ostr << "DICOMDIR";
                pathOfDicomDir = ostr.str();
        }

        //clean dicomdir file and dicomdir directory if present...
        {
                std::ostringstream ostr;
                ostr << m_pExportacionParams->m_destinationPath;
                ostr << (char) wxFileName::GetPathSeparator();
                ostr << "DICOM";
                GNC::Entorno::Instance()->RemoveDirRecursive(ostr.str());
                wxRemoveFile(FROMPATH(pathOfDicomDir));
        }
        //

        std::map<std::string, int> mapOfPathPatients;
        std::map<std::string, int> mapOfPathStudies;
        std::map<std::string, int> mapOfPathSeries;
        std::map<std::string, int> mapOfPathImages;

        std::map<std::string, DcmDirectoryRecord*> dcmMapOfPatients;
        std::map<std::string, DcmDirectoryRecord*> dcmMapOfStudies;
        std::map<std::string, DcmDirectoryRecord*> dcmMapOfSeries;

        std::string pathOfPatient, pathOfStudy, pathOfSeries;

        int patientIndex=0, studyIndex=0, seriesIndex=0;

        int numberOfSeries = m_pExportacionParams->m_seriesList.size();
        int actualSerie = 1;

        DcmDicomDir dicomDir(pathOfDicomDir.c_str(), "GINKGOCADXCD");
        DcmDirectoryRecord *   root = &(dicomDir.getRootRecord());

        //FIRST OF ALL EXPORT WITHOUT ANONYMIZE
        if (m_pExportacionParams->m_seriesList.size() > 0 && m_pExportacionParams->m_anonymized.tags.empty() && m_pExportacionParams->m_includeGinkgoTags) {
                for (ExportToDicomDirCommandParams::TListOfPks::const_iterator itUids = m_pExportacionParams->m_seriesList.begin(); itUids != m_pExportacionParams->m_seriesList.end(); ++itUids) {
                        wxString cadena = wxString::Format(_("Exporting series %d of %d"), (int)(actualSerie++), (int)(numberOfSeries));
                        if (!NotificarProgreso((float)actualSerie/numberOfSeries, std::string(cadena.ToUTF8())))
                                return;
                        //find source paths and series model
                        GNC::GCS::IHistoryController::SeriesModel seriesModel = GNC::GCS::HistoryController::Instance()->GetSeriesModel((*itUids));
                        GNC::GCS::IHistoryController::StudyModel studyModel = GNC::GCS::HistoryController::Instance()->GetStudyModel(seriesModel.study_fk);
                        GNC::GCS::IHistoryController::FileModelList fileModels;
                        GNC::GCS::HistoryController::Instance()->GetSeriesSortedFileModels((*itUids), fileModels);

                        if (fileModels.empty()) {
                                m_pExportacionParams->m_Error = _Std("Some of selected series has been deleted");
                                m_pExportacionParams->m_hasError = true;
                                return;
                        }

                        //get path of series
                        wxString fullPathWx;
                        if (!CreatePathOfSeries(studyModel, seriesModel, mapOfPathPatients, mapOfPathStudies, mapOfPathSeries, patientIndex, studyIndex, seriesIndex, m_pExportacionParams->m_destinationPath, pathOfPatient, pathOfStudy, pathOfSeries, fullPathWx) ) {
                                m_pExportacionParams->m_Error = _Std("There was an error creating directory");
                                m_pExportacionParams->m_hasError = true;
                                return;
                        }

                        //dicomdir structure
                        DcmDirectoryRecord* SeriesRecord = GetSeriesRecord(studyModel, seriesModel, dcmMapOfPatients, dcmMapOfStudies, dcmMapOfSeries, root);

                        //path is created, now we are going to copy images...
                        mapOfPathImages[seriesModel.series_iuid] = 0;
                        for (GNC::GCS::IHistoryController::FileModelList::const_iterator itDCMModels = fileModels.begin(); itDCMModels != fileModels.end(); ++itDCMModels) {
                                std::string pathOfImage;
                                {
                                        std::ostringstream ostr;
                                        ostr << "IM";
                                        ostr << mapOfPathImages[seriesModel.series_iuid]++;
                                        pathOfImage = ostr.str();
                                }

                                wxString pathOfImageWx = fullPathWx + wxFileName::GetPathSeparator() + wxString::FromUTF8(pathOfImage.c_str());
                                std::string absolutepathFile = (*itDCMModels).real_path;
                                if (!wxCopyFile(FROMPATH(absolutepathFile),  pathOfImageWx)) {
                                        LOG_ERROR("ExportToDicomDirCommand", "Error copying file " << absolutepathFile << " TO " << pathOfImageWx.ToUTF8());
                                        m_pExportacionParams->m_Error = _Std("There was an error writing file");
                                        m_pExportacionParams->m_hasError = true;
                                        return;
                                }
                                DcmDirectoryRecord* ImageRecord = new DcmDirectoryRecord();
                                SeriesRecord->insertSub(ImageRecord);
                                std::string fileId;
                                {
                                        std::ostringstream ostr;
                                        ostr << "DICOM" << "\\" << pathOfPatient << "\\" << pathOfStudy << "\\" << pathOfSeries << "\\" << pathOfImage;
                                        fileId = ostr.str();
                                }
                                InsertTagRecord(DCM_DirectoryRecordType, "IMAGE", ImageRecord);
                                InsertTagRecord(DCM_ReferencedSOPInstanceUIDInFile, (*itDCMModels).sopiuid, ImageRecord);
                                InsertTagRecord(DCM_ReferencedTransferSyntaxUIDInFile, (*itDCMModels).tsuid, ImageRecord);
                                InsertTagRecord(DCM_ReferencedSOPClassUIDInFile, (*itDCMModels).sopcuid, ImageRecord);
                                InsertTagRecord(DCM_SpecificCharacterSet, "ISO_IR 192", ImageRecord);
                                InsertTagRecord(DCM_ImageComments, (*itDCMModels).file_desc, ImageRecord);
                                std::string instanceNumber;
                                {
                                        std::ostringstream ostr;
                                        ostr << (*itDCMModels).instance_number;
                                        instanceNumber = ostr.str();
                                }
                                InsertTagRecord(DCM_InstanceNumber, instanceNumber, ImageRecord);
                                InsertTagRecord(DCM_ReferencedFileID, fileId, ImageRecord);
                        }
                }
        }///END EXPORT WITHOUT ANONYMIZE
        std::string m_TmpDir = GNC::Entorno::Instance()->CrearDirectorioTemporal();
        //export series anonymizing...
        if (m_pExportacionParams->m_seriesList.size() > 0 && (!m_pExportacionParams->m_anonymized.tags.empty() || !m_pExportacionParams->m_includeGinkgoTags)) {
                for (ExportToDicomDirCommandParams::TListOfPks::const_iterator itUids = m_pExportacionParams->m_seriesList.begin(); itUids != m_pExportacionParams->m_seriesList.end(); ++itUids) {
                        wxString cadena = wxString::Format(_("Exporting series %d of %d"), (int)(actualSerie++), (int)(numberOfSeries));
                        if (!NotificarProgreso((float)actualSerie/numberOfSeries, std::string(cadena.ToUTF8())))
                                return;
                        //find source paths and series model
                        GNC::GCS::IHistoryController::FileModelList fileModels;
                        GNC::GCS::HistoryController::Instance()->GetSeriesSortedFileModels((*itUids), fileModels);

                        for (GNC::GCS::IHistoryController::FileModelList::const_iterator itFileModel = fileModels.begin(); itFileModel != fileModels.end(); ++itFileModel) {
                                GIL::DICOM::DICOMManager manager;
                                manager.CargarFichero((*itFileModel).real_path);
                                manager.ActualizarJerarquia(m_pExportacionParams->m_anonymized);
                                if (!m_pExportacionParams->m_includeGinkgoTags) {
                                        manager.AnonimizarTagsPrivados();
                                }
                                wxString targetFile = FROMPATH(m_TmpDir) + wxFileName::GetPathSeparator() + wxString::Format(wxT("%d"), (int)(rand()));
                                while (wxFileExists(targetFile)) {
                                        targetFile = FROMPATH(m_TmpDir) + wxFileName::GetPathSeparator() + wxString::Format(wxT("%d"), (int)(rand()));
                                }
                                std::string targetFileStd(TOPATH(targetFile));
                                if (!manager.AlmacenarFichero(targetFileStd)) {
                                        m_pExportacionParams->m_Error = _Std("There was an error anonymizing files");
                                        m_pExportacionParams->m_hasError = true;
                                        return;
                                }
                        }
                }
        }
        //read tmp directory and insert into dcmdir...
        {
                wxString tmpDirWx = FROMPATH(m_TmpDir);
                wxDir dir;
                if (dir.Open(tmpDirWx)) {
                        wxString fileName;
                        bool cont = dir.GetFirst(&fileName);
                        while (cont) {
                                fileName=dir.GetName()+ wxFileName::GetPathSeparator(wxPATH_NATIVE) +fileName;
                                const std::string fileNameStd(TOPATH(fileName));
                                GNC::GCS::IHistoryController::DICOMFileModel dicomFile;
                                GNC::GCS::IHistoryController::TAddErrorList foo;
                                if (!GNC::GCS::HistoryController::Instance()->ReadFile(dicomFile, fileNameStd, foo)) {
                                        LOG_ERROR("ExportDICOMDir", "error reading " << fileNameStd);
                                        continue;
                                }

                                //create path
                                wxString fullPathWx;
                                if (!CreatePathOfSeries(dicomFile.study, dicomFile.series, mapOfPathPatients, mapOfPathStudies, mapOfPathSeries, patientIndex, studyIndex, seriesIndex, m_pExportacionParams->m_destinationPath, pathOfPatient, pathOfStudy, pathOfSeries, fullPathWx) ) {
                                        m_pExportacionParams->m_Error = _Std("There was an error creating directory");
                                        m_pExportacionParams->m_hasError = true;
                                        return;
                                }

                                //dicomdir structure
                                DcmDirectoryRecord* SeriesRecord = GetSeriesRecord(dicomFile.study, dicomFile.series, dcmMapOfPatients, dcmMapOfStudies, dcmMapOfSeries, root);

                                //path is created, now we are going to copy images...
                                if (mapOfPathImages.find(dicomFile.series.series_iuid) == mapOfPathImages.end()) {
                                        mapOfPathImages[dicomFile.series.series_iuid] = 0;
                                }
                                std::string pathOfImage;
                                {
                                        std::ostringstream ostr;
                                        ostr << "IM";
                                        ostr << mapOfPathImages[dicomFile.series.series_iuid]++;
                                        pathOfImage = ostr.str();
                                }

                                wxString pathOfImageWx = fullPathWx + wxFileName::GetPathSeparator() + wxString::FromUTF8(pathOfImage.c_str());
                                //moving tmp files...
                                if (!wxRenameFile(fileName, pathOfImageWx)) {
                                        m_pExportacionParams->m_Error = _Std("There was an error writing file");
                                        m_pExportacionParams->m_hasError = true;
                                        return;
                                }

                                DcmDirectoryRecord* ImageRecord = new DcmDirectoryRecord();
                                SeriesRecord->insertSub(ImageRecord);
                                std::string fileId;
                                {
                                        std::ostringstream ostr;
                                        ostr << "DICOM" << "\\" << pathOfPatient << "\\" << pathOfStudy << "\\" << pathOfSeries << "\\" << pathOfImage;
                                        fileId = ostr.str();
                                }
                                InsertTagRecord(DCM_ReferencedFileID, fileId, ImageRecord);
                                InsertTagRecord(DCM_DirectoryRecordType, "IMAGE", ImageRecord);
                                InsertTagRecord(DCM_ReferencedSOPInstanceUIDInFile, dicomFile.file.sopiuid, ImageRecord);
                                InsertTagRecord(DCM_ReferencedTransferSyntaxUIDInFile, dicomFile.file.tsuid, ImageRecord);
                                InsertTagRecord(DCM_ReferencedSOPClassUIDInFile, dicomFile.file.sopcuid, ImageRecord);
                                {
                                        std::ostringstream ostr;
                                        ostr << dicomFile.file.instance_number;
                                        InsertTagRecord(DCM_InstanceNumber, ostr.str(), ImageRecord);
                                }
                                InsertTagRecord(DCM_ImageComments, dicomFile.file.file_desc, ImageRecord);
                                InsertTagRecord(DCM_SpecificCharacterSet, "ISO_IR 192", ImageRecord);
                                cont = dir.GetNext(&fileName);
                        }
                }

        }
        OFCondition cond = dicomDir.write();
        std::cout << cond.text() << std::endl;
}
Esempio n. 26
0
void RegisterVSTEffects()
{
   PluginManager & pm = PluginManager::Get();

   pm.Open();

   if (gPrefs->Read(wxT("/VST/Rescan"), (long) false) != false) {
      pm.PurgeType(VSTPLUGINTYPE);
      gPrefs->Write(wxT("/VST/Rescan"), false);
   }

   if (!pm.HasType(VSTPLUGINTYPE)) {
      pm.Close();
      VSTEffect::Scan();
      pm.Open();
   }

   EffectManager & em = EffectManager::Get();

   wxString path = pm.GetFirstPlugin(VSTPLUGINTYPE);
   while (!path.IsEmpty()) {
#if defined(__WXMAC__)
      if (wxDirExists(path)) {
#else
      if (wxFileExists(path)) {
#endif
         em.RegisterEffect(new VSTEffect(path));
      }
      
      path = pm.GetNextPlugin(VSTPLUGINTYPE);
   }

   pm.Close();
}

///////////////////////////////////////////////////////////////////////////////
//
// VSTEffectDialog
//
///////////////////////////////////////////////////////////////////////////////

class VSTEffectDialog:public wxDialog, XMLTagHandler
{
 public:
   VSTEffectDialog(wxWindow * parent,
                   const wxString & title,
                   VSTEffect *effect,
                   AEffect *aeffect);
   virtual ~VSTEffectDialog();

   void RemoveHandler();

   void OnIdle(wxIdleEvent & evt);

   void OnProgram(wxCommandEvent & evt);
   void OnProgramText(wxCommandEvent & evt);
   void OnLoad(wxCommandEvent & evt);
   void OnSave(wxCommandEvent & evt);

   void OnSlider(wxCommandEvent &event);

   void OnOk(wxCommandEvent & evt);
   void OnCancel(wxCommandEvent & evt);
   void OnClose(wxCloseEvent & evt);
   void OnPreview(wxCommandEvent & evt);

 private:
Esempio n. 27
0
bool
PrivKey::canLoad(void) const
{
    return (wxFileExists(keyFile_));
}
Esempio n. 28
0
File: file.cpp Progetto: EdgarTx/wx
bool wxFile::Exists(const wxChar *name)
{
    return wxFileExists(name);
}
Esempio n. 29
0
bool PluginManager::ExportPlugin(cbPlugin* plugin, const wxString& filename)
{
    if (!plugin)
        return false;

    wxArrayString sourcefiles;
    wxArrayString extrafiles;
    wxArrayString extrafilesdest;
    wxFileName fname;
    wxString resourceFilename;

    // find the plugin element
    for (size_t i = 0; i < m_Plugins.GetCount(); ++i)
    {
        PluginElement* elem = m_Plugins[i];
        if (elem && elem->plugin == plugin)
        {
            // got it

            // plugin file
            sourcefiles.Add(elem->fileName);
            fname.Assign(elem->fileName);

            // now get the resource zip filename
            resourceFilename = fname.GetName() + _T(".zip");
            if (!platform::windows && resourceFilename.StartsWith(_T("lib")))
                resourceFilename.Remove(0, 3);
            resourceFilename = ConfigManager::LocateDataFile(resourceFilename, sdDataGlobal | sdDataUser);
            sourcefiles.Add(resourceFilename);

            // the highlighted icon the plugin may have for its "settings" page
            resourceFilename = fname.GetName() + _T(".png");
            if (!platform::windows && resourceFilename.StartsWith(_T("lib")))
                resourceFilename.Remove(0, 3);
            resourceFilename.Prepend(_T("images/settings/"));
            resourceFilename = ConfigManager::LocateDataFile(resourceFilename, sdDataGlobal | sdDataUser);
            if (!resourceFilename.IsEmpty())
                sourcefiles.Add(resourceFilename);

            // the non-highlighted icon the plugin may have for its "settings" page
            resourceFilename = fname.GetName() + _T("-off.png");
            if (!platform::windows && resourceFilename.StartsWith(_T("lib")))
                resourceFilename.Remove(0, 3);
            resourceFilename.Prepend(_T("images/settings/"));
            resourceFilename = ConfigManager::LocateDataFile(resourceFilename, sdDataGlobal | sdDataUser);
            if (!resourceFilename.IsEmpty())
                sourcefiles.Add(resourceFilename);

            // export extra files
            resourceFilename = fname.GetName() + _T(".zip");
            if (!platform::windows && resourceFilename.StartsWith(_T("lib")))
                resourceFilename.Remove(0, 3);
            ReadExtraFilesFromManifestFile(resourceFilename, extrafilesdest);
            for (size_t n = 0; n < extrafilesdest.GetCount(); ++n)
            {
                extrafiles.Add(ConfigManager::LocateDataFile(extrafilesdest[n], sdDataGlobal | sdDataUser));
            }

            break;
        }
    }

    if (wxFileExists(filename))
    {
        if (!wxFile::Access(filename, wxFile::write))
        {
            cbMessageBox(wxString::Format(_("%s is in use.\nAborting..."), filename.c_str()),
                        _("Warning"), wxICON_WARNING);
            return false;
        }
    }

//    Manager::Get()->GetLogManager()->DebugLog(F(_T("Creating archive: ") + filename));
    wxFileOutputStream out(filename);
    wxZipOutputStream zip(out, 9); // max compression
    for (size_t i = 0; i < sourcefiles.GetCount(); ++i)
    {
        if (sourcefiles[i].IsEmpty())
            continue;

        wxFileInputStream in(sourcefiles[i]);
        zip.PutNextEntry(wxFileName(sourcefiles[i]).GetFullName());
        zip << in;
    }
    for (size_t i = 0; i < extrafiles.GetCount(); ++i)
    {
        if (extrafiles[i].IsEmpty() || extrafilesdest[i].IsEmpty())
            continue;

        wxFileInputStream in(extrafiles[i]);

        zip.PutNextEntry(extrafilesdest[i]);
        zip << in;
    }
    zip.SetComment(_T("This is a redistributable plugin for the Code::Blocks IDE.\n"
                        "See http://www.codeblocks.org for details..."));

    return true;
}
Esempio n. 30
0
void CallGraph::OnShowCallGraph(wxCommandEvent& event)
{
    // myLog("wxThread::IsMain(%d)", (int)wxThread::IsMain());

    IConfigTool *config_tool = m_mgr->GetConfigTool();

    config_tool->ReadObject(wxT("CallGraph"), &confData);

    if (!wxFileExists(GetGprofPath()) || !wxFileExists(GetDotPath()))
        return MessageBox(_T("Failed to locate required tools (gprof, dot). Please check the plugin settings."), wxICON_ERROR);

    Workspace   *ws = m_mgr->GetWorkspace();
    if (!ws)		return MessageBox(_("Unable to get opened workspace."), wxICON_ERROR);

    wxFileName  ws_cfn = ws->GetWorkspaceFileName();

    wxString projectName = ws->GetActiveProjectName();

    BuildMatrixPtr	  mtx = ws->GetBuildMatrix();
    if (!mtx)	   return MessageBox(_("Unable to get current build matrix."), wxICON_ERROR);

    wxString	build_config_name = mtx->GetSelectedConfigurationName();

    BuildConfigPtr	  bldConf = ws->GetProjBuildConf(projectName, build_config_name);
    if (!bldConf)   return MessageBox(_("Unable to get opened workspace."), wxICON_ERROR);

    wxString	projOutputFn = bldConf->GetOutputFileName();
    wxString	projWorkingDir = bldConf->GetWorkingDirectory();

    /*
    myLog("WorkspaceFileName = \"%s\"", ws_cfn.GetFullPath());
    myLog("projectName \"%s\"", projectName);
    myLog("build_config_name = \"%s\"", build_config_name);
    myLog("projOutputFn = \"%s\"", projOutputFn);
    myLog("projWorkingDir = \"%s\"", projWorkingDir);
    */

    wxFileName  cfn(ws_cfn.GetPath(), projOutputFn);
    cfn.Normalize();

    // base path
    const wxString	base_path = ws_cfn.GetPath();

    // check source binary exists
    wxString	bin_fpath = cfn.GetFullPath();
    if (!cfn.Exists()) {
        bin_fpath = wxFileSelector("Please select the binary to analyze", base_path, "", "");
        if (bin_fpath.IsEmpty())		return MessageBox("selected binary was canceled", wxICON_ERROR);

        cfn.Assign(bin_fpath, wxPATH_NATIVE);
    }
    if (!cfn.IsFileExecutable())		return MessageBox("bin/exe isn't executable", wxICON_ERROR);

    // check 'gmon.out' file exists
    wxFileName  gmon_cfn(base_path, GMON_FILENAME_OUT);
    if (!gmon_cfn.Exists())
        gmon_cfn.Normalize();

    wxString	gmonfn = gmon_cfn.GetFullPath();
    if (!gmon_cfn.Exists()) {
        gmonfn = wxFileSelector("Please select the gprof file", gmon_cfn.GetPath(), "gmon", "out");
        if (gmonfn.IsEmpty())		return MessageBox("selected gprof was canceled", wxICON_ERROR);

        gmon_cfn.Assign(gmonfn, wxPATH_NATIVE);
    }

    wxString	bin, arg1, arg2;

    bin = GetGprofPath();
    arg1 = bin_fpath;
    arg2 = gmonfn;

    wxString cmdgprof = wxString::Format("%s %s %s", bin, arg1, arg2);

    // myLog("about to wxExecute(\"%s\")", cmdgprof);

    wxProcess	*proc = new wxProcess(wxPROCESS_REDIRECT);

    // wxStopWatch	sw;

    const int	err = ::wxExecute(cmdgprof, wxEXEC_SYNC, proc);
    // on sync returns 0 (success), -1 (failure / "couldn't be started")

    // myLog("wxExecute() returned err %d, had pid %d", err, (int)proc->GetPid());

    wxInputStream	   *process_is = proc->GetInputStream();
    if (!process_is || !process_is->CanRead())
        return MessageBox(_("wxProcess::GetInputStream() can't be opened, aborting"), wxICON_ERROR);

    // start parsing and writing to dot language file
    GprofParser pgp;

    pgp.GprofParserStream(process_is);

    // myLog("gprof done (read %d lines)", (int) pgp.lines.GetCount());

    delete proc;

    ConfCallGraph conf;

    config_tool->ReadObject(wxT("CallGraph"), &conf);

    DotWriter dotWriter;

    // DotWriter
    dotWriter.SetLineParser(&(pgp.lines));

    int suggestedThreshold = pgp.GetSuggestedNodeThreshold();

    if (suggestedThreshold <= conf.GetTresholdNode()) {
        suggestedThreshold = conf.GetTresholdNode();

        dotWriter.SetDotWriterFromDialogSettings(m_mgr);

    } else {
        dotWriter.SetDotWriterFromDetails(conf.GetColorsNode(),
                                          conf.GetColorsEdge(),
                                          suggestedThreshold,
                                          conf.GetTresholdEdge(),
                                          conf.GetHideParams(),
                                          conf.GetStripParams(),
                                          conf.GetHideNamespaces());

        wxString	suggest_msg = wxString::Format(_("The CallGraph plugin has suggested node threshold %d to speed-up the call graph creation. You can alter it on the call graph panel."), suggestedThreshold);

        MessageBox(suggest_msg, wxICON_INFORMATION);
    }

    dotWriter.WriteToDotLanguage();

    // build output dir
    cfn.Assign(base_path, "");
    cfn.AppendDir(CALLGRAPH_DIR);
    cfn.Normalize();

    if (!cfn.DirExists())	   cfn.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

    cfn.SetFullName(DOT_FILENAME_TXT);
    wxString dot_fn = cfn.GetFullPath();

    dotWriter.SendToDotAppOutputDirectory(dot_fn);

    cfn.SetFullName(DOT_FILENAME_PNG);
    wxString output_png_fn = cfn.GetFullPath();

    // delete any existing PNG
    if (wxFileExists(output_png_fn))	wxRemoveFile(output_png_fn);

    wxString cmddot_ln;

    cmddot_ln << GetDotPath() << " -Tpng -o" << output_png_fn << " " << dot_fn;

    // myLog("wxExecute(\"%s\")", cmddot_ln);

    wxExecute(cmddot_ln, wxEXEC_SYNC);

    // myLog("dot done");

    if (!wxFileExists(output_png_fn))
        return MessageBox(_("Failed to open file CallGraph.png. Please check the project settings, rebuild the project and try again."), wxICON_INFORMATION);

    // show image and create table in the editor tab page
    uicallgraphpanel	*panel = new uicallgraphpanel(m_mgr->GetEditorPaneNotebook(), m_mgr, output_png_fn, base_path, suggestedThreshold, &(pgp.lines));

    wxString	tstamp = wxDateTime::Now().Format(wxT(" %Y-%m-%d %H:%M:%S"));

    wxString	  title = wxT("Call graph for \"") + output_png_fn + wxT("\" " + tstamp);

    m_mgr->AddEditorPage(panel, title);
}