Пример #1
0
/*! 
 *
 * Starts the job running and sets the status code to STATUS_RUNNING.
 * 
 * The windows implementation of this function opens a new process for
 * GAMESS and redirects stdout to a log file handle and redirects
 * stderr to NUL. The process is created in a suspended state, and the
 * added to a new windows job object before it is resumed.
 *
 * \par Notes of explanation concerning the implementation of Start:
 * In order to make cshell happy, you must provide it with valid standard
 * output and standard error handles. If either of the above is missing, cshell
 * will simply quit with an exit status of 1, and nothing will happen. Standard
 * output goes to the log file anyway, so that one is obvious. In order to
 * provide a valid standard error handle, I used the windows NUL file.
 *
 * \par
 * The process is created in a suspended state, added to the job object and
 * then resumed. The reason for this is because when you run a script with
 * cshell, the first thing it will do is fork and start running other processes
 * as described by the shell script. In order to make sure that all of its sub
 * processes are part of the job object, it must be added to the job object
 * before it has a chance to do anything. Since we have no guarantee as to when
 * the sub-process will start getting processor time, it is suspended until we
 * know it has been added to the job object.
 *
 * \sa WindowsJob::mProcessHandle
 * \sa WindowsJob::mJobHandle
 */
void WindowsJob::Start()
{
	// set this here, so we don't accidentally start it twice
	mStatus = STATUS_RUNNING;

	// try to find gamess
	wxString gamessname;
	if (gamessDir.IsEmpty()) {
		wxPathList SystemPath;
		SystemPath.AddEnvList(wxT("PATH"));
		gamessname = SystemPath.FindAbsoluteValidPath(wxT("rungms.bat"));
	} else {
		wxFileName name(gamessDir, wxT("rungms.bat"));
		name.MakeAbsolute();
		gamessname = name.GetFullPath();
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}

#ifdef DEFAULT_GAMESS_PATH
	if (gamessname.IsEmpty()) {
		wxStandardPathsBase& gStdPaths = wxStandardPaths::Get();
		gamessname = gStdPaths.GetResourcesDir() + wxT(DEFAULT_GAMESS_PATH) +
				wxT("/rungms.bat");
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}
#endif

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

	// clean up old temp stuff so ddikick doesn't fail
	CleanUpTempFiles();

	wxFileName dest(GetSpoolFileName());
	dest = wxFileName(gamessDir + wxT("\\scratch"), dest.GetName());
	dest.SetExt(wxT("F05"));
	wxString debug = wxT("Copying file from ") + GetSpoolFileName();
	debug << wxT(" to ") << dest.GetFullPath();
	wxLogDebug(debug);
	wxCopyFile(GetSpoolFileName(), dest.GetFullPath(), true);


	// generate the command
	wxFileName name(gamessname);
	name.SetFullName(wxT("rungms.bat"));
//	name.SetFullName(wxT("csh.exe"));
//	name.MakeAbsolute();
	wxString command = name.GetFullPath();
//	name.SetFullName(wxT("runscript.csh"));
//	command << wxT(" -e -f ") << name.GetFullPath();
	name = wxFileName(GetSpoolFileName());
	command << wxT(" ") << name.GetName();
	command << wxT(" 13-64.pgi.linux.blas ");
	command << mNumProcessors;
//	command << wxT(" ") << gamessDir;
//	command << wxT(" ") << wxGetHostName();
	wxLogMessage(wxT("Exec: ") + command);

	// set up the security attributes for the input and output handles
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = true;

	// create a the log file and it's handle
	name.SetExt(wxT("log"));
	name.MakeAbsolute();
	HANDLE logFileHandle = CreateFile(name.GetFullPath(), GENERIC_WRITE,
			FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
	if (logFileHandle == INVALID_HANDLE_VALUE) {
		LOG_ERROR("CreateFile");
	}

	// make a null handle for stderr
	HANDLE nullHandle = CreateFile(wxT("NUL"), GENERIC_WRITE,
			FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
	if (nullHandle == INVALID_HANDLE_VALUE) {
		LOG_ERROR("CreateFile");
	}

	// create a new STARTUPINFO object with the newly created handles
	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.wShowWindow=SW_HIDE; // hide the window
	si.dwFlags=STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
	si.hStdOutput = logFileHandle;
	si.hStdInput = NULL;
	si.hStdError = nullHandle;

	// create a new PROCESS_INFORMATION object
	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));

	// create a new job
	mJobHandle = CreateJobObject(NULL, NULL);
	if (! mJobHandle) {
		LOG_ERROR("CreateJobObject");
	}

	// now we create the actual process, it needs to be created in a suspended
	// state so that we can assign it to the job object before it gets a chance
	// to spawn any more processes.
	if (CreateProcess(NULL, (wxChar *)command.wc_str(), NULL, NULL, true,
		CREATE_SUSPENDED, NULL, spoolDir, &si, &pi)) {
		if (! AssignProcessToJobObject(mJobHandle, pi.hProcess)) {
			LOG_ERROR("AssignProcessToJobObject");
		}
		mProcessHandle = pi.hProcess;
		ResumeThread(pi.hThread);
	} else {
		mStatus = STATUS_ERROR;
		LOG_ERROR("CreateProcess");
		mStatus = STATUS_ERROR;
		mProcessHandle = NULL;
		CloseHandle(pi.hProcess);
	}

	// close our side of the IO handles
	CloseHandle(logFileHandle);
	CloseHandle(nullHandle);

	// we don't need this one anymore
	CloseHandle(pi.hThread);
}
Пример #2
0
bool NativeFileSystem::CopyFile(const std::string & file, const std::string & destination)
{
    wxLogNull noLogPlease;
    return wxCopyFile( file, destination, true );
}
Пример #3
0
bool SaveXmlFile(const wxFileName& file, TiXmlNode* node, wxString* error /*=0*/, bool move /*=false*/)
{
	if (!node)
		return true;

	const wxString& fullPath = file.GetFullPath();

	TiXmlDocument* pDocument = node->GetDocument();

	bool exists = false;

	bool isLink = false;
	int flags = 0;
	if (CLocalFileSystem::GetFileInfo( fullPath, isLink, 0, 0, &flags ) == CLocalFileSystem::file)
	{
#ifdef __WXMSW__
		if (flags & FILE_ATTRIBUTE_HIDDEN)
			SetFileAttributes(fullPath, flags & ~FILE_ATTRIBUTE_HIDDEN);
#endif

		exists = true;
		bool res;
		if (!move)
		{
			wxLogNull null;
			res = wxCopyFile(fullPath, fullPath + _T("~"));
		}
		else
		{
			wxLogNull null;
			res = wxRenameFile(fullPath, fullPath + _T("~"));
		}
		if (!res)
		{
			const wxString msg = _("Failed to create backup copy of xml file");
			if (error)
				*error = msg;
			else
				wxMessageBoxEx(msg);
			return false;
		}
	}

	wxFFile f(fullPath, _T("w"));
	if (!f.IsOpened() || !pDocument->SaveFile(f.fp()))
	{
		wxRemoveFile(fullPath);
		if (exists)
		{
			wxLogNull null;
			wxRenameFile(fullPath + _T("~"), fullPath);
		}
		const wxString msg = _("Failed to write xml file");
		if (error)
			*error = msg;
		else
			wxMessageBoxEx(msg);
		return false;
	}

	if (exists)
		wxRemoveFile(fullPath + _T("~"));

	return true;
}
bool palm_installer::install_files_by_handheld_dest( handheld_dest_type& handheld_dest,
        wxArrayString& install_fullnames )
{
    wxString    destination_fullname;
    wxString    destination_path;
    wxString    destination_rootpath;
    wxString    destination_basename;
    wxString    destination_extension;
    int         user_index;
    wxString    install_fullname;
    bool        install_fullname_exists = false;
    bool        successful              = false;

    // This is a dummy to induce a translatable string, when we want the original to stay as untranslated.
    wxString 	dummy1 = _( "SecureDigital (SD) Card" );

    wxLogDebug( wxT( "Entering palm_installer::install_files_by_handheld_dest function" ) );

    // If wxArrayString is empty, then abort
    if ( install_fullnames.IsEmpty() )
    {
        wxLogDebug( "Error: no filenames sent to install_files_by_handheld_dest. Aborting..." );
        return false;
    }

    // Look up the user_index of this user_name
    user_index = get_user_index_from_user_name( handheld_dest.user_name );

    if ( get_number_of_users() > 0 )
    {
        destination_rootpath = get_palm_desktop_path() + "/"
                               + get_user_subdirectory( user_index );

        // If installing to card, use that path...
        switch (  handheld_dest.handheld_target_storage_mode )
        {
        case plkrHANDHELD_TARGET_STORAGE_MODE_SD_CARD:
            destination_path = get_translated_handheld_destination_path( destination_rootpath,
                               "SecureDigital (SD) Card",
                               "SecureDigital"
                                                                       );
            break;
        case plkrHANDHELD_TARGET_STORAGE_MODE_MEMORY_STICK:
            destination_path = destination_rootpath + "/Files to Install/Memory Stick";
            break;
        case plkrHANDHELD_TARGET_STORAGE_MODE_COMPACT_FLASH:
            destination_path = destination_rootpath + "/Files to Install/Compact Flash Card";
            break;
        // default is the normal RAM one.
        default:
            destination_path = destination_rootpath + "/Files to Install";
            break;
        }

        // Check the destination rootpath exists. It may not, if it was a newly created
        // user, it may not have its directory yet
        wxLogDebug( "destination_rootpath=" + destination_rootpath );

        // If this is a brand new user, won't have an "Install" subdirectory
        // in his/her directory yet, so create it, if not there yet.
        if ( ! wxDirExists( destination_path ) )
        {
            wxLogDebug( "destination_path not exist, so making..." );

            // If the "Files to Install" doesn't exist, then need to make that, before can
            // make a dir such as "Memory Stick" inside of that.
            if ( ! wxDirExists ( destination_rootpath + "/Files to Install" ) )
            {
                wxMkdir( destination_rootpath + "/Files to Install", 0777 );
            }

            // OK: can now make the SecureDigital (SD) Card or Memory Stick dir
            // if destination is a card (or the "Files to Install" dir if not card).
            wxMkdir( destination_path, 0777 );
        }

        for ( size_t n = 0; n < install_fullnames.GetCount(); n++ )
        {
            wxLogDebug( "Starting loop to install" );
            install_fullname = install_fullnames.Item( n );
            wxLogDebug( "install_fullname=" + install_fullname );
            install_fullname_exists = wxFileExists( install_fullname );

            if ( install_fullname_exists )
            {
                // Get the basename and extension, so it can have the same basename + extension
                // in the install directory.
                wxSplitPath( install_fullname.c_str(), NULL, &destination_basename,
                             &destination_extension );

                destination_fullname = destination_path + "/" + destination_basename
                                       + '.' + destination_extension;

                // Copy the file over.
                if ( wxCopyFile( install_fullname, destination_fullname, TRUE ) )
                {
                    successful = TRUE;
                }
                else
                {
                    wxLogError( "Error: couldn't copy " + install_fullname + " to " + destination_fullname );
                }

            }
            else
            {
                wxLogDebug( "Error: install_fullname " + install_fullname + " doesn't exist" );
            }
        }
    }

    return successful;
}
Пример #5
0
bool wxMakeMetafilePlaceable(const wxString& filename, int x1, int y1, int x2, int y2, float scale, bool useOriginAndExtent)
{
    // I'm not sure if this is the correct way of suggesting a scale
    // to the client application, but it's the only way I can find.
    int unitsPerInch = (int)(576/scale);

    mfPLACEABLEHEADER header;
    header.key = 0x9AC6CDD7L;
    header.hmf = 0;
    header.bbox.left = (int)(x1);
    header.bbox.top = (int)(y1);
    header.bbox.right = (int)(x2);
    header.bbox.bottom = (int)(y2);
    header.inch = unitsPerInch;
    header.reserved = 0;

    // Calculate checksum
    WORD *p;
    mfPLACEABLEHEADER *pMFHead = &header;
    for (p =(WORD *)pMFHead,pMFHead -> checksum = 0;
            p < (WORD *)&pMFHead ->checksum; ++p)
        pMFHead ->checksum ^= *p;

    FILE *fd = wxFopen(filename.fn_str(), wxT("rb"));
    if (!fd) return false;

    wxString tempFileBuf = wxFileName::CreateTempFileName(wxT("mf"));
    if (tempFileBuf.empty())
        return false;

    FILE *fHandle = wxFopen(tempFileBuf.fn_str(), wxT("wb"));
    if (!fHandle)
        return false;
    fwrite((void *)&header, 1, sizeof(mfPLACEABLEHEADER), fHandle);

    // Calculate origin and extent
    int originX = x1;
    int originY = y1;
    int extentX = x2 - x1;
    int extentY = (y2 - y1);

    // Read metafile header and write
    METAHEADER metaHeader;
    fread((void *)&metaHeader, 1, sizeof(metaHeader), fd);

    if (useOriginAndExtent)
        metaHeader.mtSize += 15;
    else
        metaHeader.mtSize += 5;

    fwrite((void *)&metaHeader, 1, sizeof(metaHeader), fHandle);

    // Write SetMapMode, SetWindowOrigin and SetWindowExt records
    char modeBuffer[8];
    char originBuffer[10];
    char extentBuffer[10];
    METARECORD *modeRecord = (METARECORD *)&modeBuffer;

    METARECORD *originRecord = (METARECORD *)&originBuffer;
    METARECORD *extentRecord = (METARECORD *)&extentBuffer;

    modeRecord->rdSize = 4;
    modeRecord->rdFunction = META_SETMAPMODE;
    modeRecord->rdParm[0] = MM_ANISOTROPIC;

    originRecord->rdSize = 5;
    originRecord->rdFunction = META_SETWINDOWORG;
    originRecord->rdParm[0] = originY;
    originRecord->rdParm[1] = originX;

    extentRecord->rdSize = 5;
    extentRecord->rdFunction = META_SETWINDOWEXT;
    extentRecord->rdParm[0] = extentY;
    extentRecord->rdParm[1] = extentX;

    fwrite((void *)modeBuffer, 1, 8, fHandle);

    if (useOriginAndExtent)
    {
        fwrite((void *)originBuffer, 1, 10, fHandle);
        fwrite((void *)extentBuffer, 1, 10, fHandle);
    }

    int ch = -2;
    while (ch != EOF)
    {
        ch = getc(fd);
        if (ch != EOF)
        {
            putc(ch, fHandle);
        }
    }
    fclose(fHandle);
    fclose(fd);
    wxRemoveFile(filename);
    wxCopyFile(tempFileBuf, filename);
    wxRemoveFile(tempFileBuf);
    return true;
}
Пример #6
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;
}
Пример #7
0
cbProject* TemplateManager::NewProjectFromUserTemplate(NewFromTemplateDlg& dlg, wxString* pFilename)
{
    cbProject* prj = NULL;
    if (!dlg.SelectedUserTemplate())
    {
        Manager::Get()->GetLogManager()->DebugLog(_T("TemplateManager::NewProjectFromUserTemplate() called when no user template was selected ?!?"));
        return NULL;
    }

    wxString path = Manager::Get()->GetConfigManager(_T("template_manager"))->Read(_T("/projects_path"));
    wxString sep = wxFileName::GetPathSeparator();
    // select directory to copy user template files
    path = ChooseDirectory(0, _("Choose a directory to create the new project"),
                        path, _T(""), false, true);
    if (path.IsEmpty())
    {
        return NULL;
    }
    else if(path.Mid(path.Length() - 1) == wxFILE_SEP_PATH)
    {
        path.RemoveLast();
    }

    // check for existing files; if found, notify about overwriting them
    wxDir dir(path);
    if (dir.HasFiles() || dir.HasSubDirs())
    {
        if (cbMessageBox(path + _(" already contains other files.\n"
                                "If you continue, files with the same names WILL BE OVERWRITTEN.\n"
                                "Are you sure you want to continue?"),
                                _("Files exist in directory"), wxICON_EXCLAMATION | wxYES_NO | wxNO_DEFAULT) != wxID_YES)
        {
            return 0;
        }
    }

    wxBusyCursor busy;

    wxString templ = ConfigManager::GetConfigFolder() + wxFILE_SEP_PATH + _T("UserTemplates");
    templ << sep << dlg.GetSelectedUserTemplate();
    if (!wxDirExists(templ))
    {
        #if wxCHECK_VERSION(2, 9, 0)
        Manager::Get()->GetLogManager()->DebugLog(F(_T("Cannot open user-template source path '%s'!"), templ.wx_str()));
        #else
        Manager::Get()->GetLogManager()->DebugLog(F(_T("Cannot open user-template source path '%s'!"), templ.c_str()));
        #endif
        return NULL;
    }

    // copy files
    wxString project_filename;
    wxArrayString files;
    wxDir::GetAllFiles(templ, &files);
    int count = 0;
    int total_count = files.GetCount();
    for (size_t i = 0; i < files.GetCount(); ++i)
    {
        wxFileName dstname(files[i]);
        dstname.MakeRelativeTo(templ + sep);
        wxString src = files[i];
        wxString dst = path + sep + dstname.GetFullPath();
//        Manager::Get()->GetLogManager()->DebugLog("dst=%s, dstname=%s", dst.c_str(), dstname.GetFullPath().c_str());
        if (!CreateDirRecursively(dst))
            Manager::Get()->GetLogManager()->DebugLog(_T("Failed creating directory for ") + dst);
        if (wxCopyFile(src, dst, true))
        {
            if (FileTypeOf(dst) == ftCodeBlocksProject)
                project_filename = dst;
            ++count;
        }
        else
            #if wxCHECK_VERSION(2, 9, 0)
            Manager::Get()->GetLogManager()->DebugLog(F(_T("Failed copying %s to %s"), src.wx_str(), dst.wx_str()));
            #else
            Manager::Get()->GetLogManager()->DebugLog(F(_T("Failed copying %s to %s"), src.c_str(), dst.c_str()));
            #endif
    }
    if (count != total_count)
        cbMessageBox(_("Some files could not be loaded with the template..."), _("Error"), wxICON_ERROR);
    else
    {
        // open new project
        if (project_filename.IsEmpty())
            cbMessageBox(_("User-template saved successfully but no project file exists in it!"));
        else
        {
            // ask to rename the project file, if need be
            wxFileName fname(project_filename);
            wxString newname = wxGetTextFromUser(_("If you want, you can change the project's filename here (without extension):"), _("Change project's filename"), fname.GetName());
            if (!newname.IsEmpty() && newname != fname.GetName())
            {
                fname.SetName(newname);
                wxRenameFile(project_filename, fname.GetFullPath());
                project_filename = fname.GetFullPath();
            }
            prj = Manager::Get()->GetProjectManager()->LoadProject(project_filename);
            if(prj && !newname.IsEmpty())
            {
                prj->SetTitle(newname);
                for (int i = 0; i < prj->GetBuildTargetsCount(); ++i)
                {
                    ProjectBuildTarget* bt = prj->GetBuildTarget(i);
                    wxString outputFileName = bt->GetOutputFilename();
                    wxFileName outFname(outputFileName);
                    if (bt->GetTargetType() == ttLibrary)
                    {
                        Compiler* projectCompiler = CompilerFactory::GetCompiler(bt->GetCompilerID());
                        if (projectCompiler)
                            newname.Prepend(projectCompiler->GetSwitches().libPrefix);
                    }
                    outFname.SetName(newname);
                    bt->SetOutputFilename(outFname.GetFullPath());
                }
                Manager::Get()->GetProjectManager()->RebuildTree(); // so the tree shows the new name
                CodeBlocksEvent evt(cbEVT_PROJECT_OPEN, 0, prj);
                Manager::Get()->ProcessEvent(evt);
            }
        }
    }
    if (prj && pFilename)
        *pFilename = prj->GetFilename();
    return prj;
}
Пример #8
0
// Save the document
bool ctConfigToolDoc::OnSaveDocument(const wxString& filename)
{
    wxBusyCursor cursor;

    const wxString strOldPath(GetFilename());

    // Do some backing up first

    // This is the backup filename
    wxString backupFilename(filename);
    backupFilename += wxT(".bak");

    // This is the temporary copy of the backup
    wxString tempFilename(filename);
    tempFilename += wxT(".tmp");
    if (wxFileExists(tempFilename))
        wxRemoveFile(tempFilename);

    bool leaveBackup = true;

    bool saved = DoSave(tempFilename);

    if (saved)
    {
        // Remove the old .bak file
        if (wxFileExists(backupFilename))
        {
            wxRemoveFile(backupFilename);
        }

        // Copy the old file to the .bak

        if (leaveBackup)
        {
            if (wxFileExists(filename))
            {
                if (!wxRenameFile(filename, backupFilename))
                {
                    wxCopyFile(filename, backupFilename);
                    wxRemoveFile(filename);
                }
            }
        }
        else
        {
            if (wxFileExists(filename))
                wxRemoveFile(filename);
        }

        // Finally, copy the temporary file to the proper filename
        if (!wxRenameFile(tempFilename, filename))
        {
            wxCopyFile(tempFilename, filename);
            wxRemoveFile(tempFilename);
        }

        Modify(false);
        ((ctConfigToolView*)GetFirstView())->OnChangeFilename();
        SetDocumentSaved(true);
        SetFilename(filename);
        wxGetApp().GetSettings().m_lastFilename = filename;
    } else
    {
        SetFilename(strOldPath);
    }
    wxGetApp().GetMainFrame()->UpdateFrameTitle();
    return saved;
}
Пример #9
0
	// FIXME
	bool wxw_CopyFile(LPCWSTR existingFile, LPCWSTR newFile, bool overwrite)
	{
		return wxCopyFile(wxString(existingFile), wxString(newFile), overwrite);
	}
Пример #10
0
void CodeBlocksImporter::GenerateFromWorkspace(GenericWorkspacePtr genericWorkspace)
{
    GenericProjectDataListType genericProjectDataList;
    wxCopyFile(wsInfo.GetFullPath(), wsInfo.GetFullPath() + wxT(".backup"));
    wxXmlDocument codeBlocksProject;
    if(codeBlocksProject.Load(wsInfo.GetFullPath())) {
        wxXmlNode* root = codeBlocksProject.GetRoot();
        if(root) {
            wxXmlNode* rootChild = root->GetChildren();

            while(rootChild) {
                if(rootChild->GetName() == wxT("Workspace")) {
                    wxXmlNode* workspaceChild = rootChild->GetChildren();

                    while(workspaceChild) {
                        if(workspaceChild->GetName() == wxT("Project") &&
                           workspaceChild->HasAttribute(wxT("filename"))) {
                            wxString filename = workspaceChild->GetAttribute(wxT("filename"));
                            filename.Replace(wxT("\\"), wxT("/"));
                            wxFileName filenameInfo(filename);

                            GenericProjectDataType genericProjectData;
                            genericProjectData[wxT("projectFullPath")] =
                                wsInfo.GetPath() + wxFileName::GetPathSeparator() + filename;

                            wxString deps = wxT("");
                            wxXmlNode* projectChild = workspaceChild->GetChildren();
                            while(projectChild) {
                                if(projectChild->GetName() == wxT("Depends") &&
                                   projectChild->HasAttribute(wxT("filename"))) {
                                    wxString filename = projectChild->GetAttribute(wxT("filename"));
                                    wxString projectFullPath =
                                        wsInfo.GetPath() + wxFileName::GetPathSeparator() + filename;

                                    wxXmlDocument depsProject;
                                    if(depsProject.Load(projectFullPath)) {
                                        wxXmlNode* rootDeps = depsProject.GetRoot();
                                        if(rootDeps) {
                                            wxXmlNode* rootDepsChild = rootDeps->GetChildren();

                                            while(rootDepsChild) {
                                                if(rootDepsChild->GetName() == wxT("Project")) {
                                                    wxXmlNode* projectDepsChild = rootDepsChild->GetChildren();

                                                    while(projectDepsChild) {
                                                        if(projectDepsChild->GetName() == wxT("Option") &&
                                                           projectDepsChild->HasAttribute(wxT("title"))) {
                                                            wxString title =
                                                                projectDepsChild->GetAttribute(wxT("title"));
                                                            deps += title + wxT(";");
                                                        }

                                                        projectDepsChild = projectDepsChild->GetNext();
                                                    }
                                                }

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

                                projectChild = projectChild->GetNext();
                            }

                            genericProjectData[wxT("projectDeps")] = deps;

                            genericProjectDataList.push_back(genericProjectData);
                        }

                        workspaceChild = workspaceChild->GetNext();
                    }
                }

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

    for(GenericProjectDataType& genericProjectData : genericProjectDataList) {
        GenerateFromProject(genericWorkspace, genericProjectData);
    }
}
Пример #11
0
bool XLPGo(void)
{
  xlpBlockId = 0;

  if (!InputFile.empty() && !OutputFile.empty())
  {
    Contents = wxFopen(TmpContentsName, _T("w"));
    Chapters = wxFopen(_T("chapters.xlp"), _T("w"));
    Sections = wxFopen(_T("sections.xlp"), _T("w"));
    Subsections = wxFopen(_T("subsections.xlp"), _T("w"));
    Subsubsections = wxFopen(_T("subsubsections.xlp"), _T("w"));
    Index = wxFopen(_T("index.xlp"), _T("w"));

    // Insert invisible section marker at beginning
    wxFprintf(Chapters, _T("\\hy-%d{%ld}{%s}\n"),
                hyBLOCK_INVISIBLE_SECTION, NewBlockId(), _T("\n"));

    wxFprintf(Contents, _T("\\hy-%d{%ld}{%s}\n\n"),
//                hyBLOCK_LARGE_HEADING, NewBlockId(), "\n\n%s\n\n", ContentsNameString);
                hyBLOCK_LARGE_HEADING, NewBlockId(), ContentsNameString);

    SetCurrentOutput(Chapters);

    wxFprintf(Index, _T("\n\\hyindex{\n\"%s\"\n"),
             contentsString ? contentsString : _T("WXHELPCONTENTS"));
    TraverseDocument();

    wxNode *node = hyperLinks.GetFirst();
    while (node)
    {
      long from = node->GetKeyInteger();
      wxChar *label = (wxChar *)node->GetData();
      wxNode *otherNode = hyperLabels.Find(label);
      if (otherNode)
      {
        long to = (long)otherNode->GetData();
        wxFprintf(Index, _T("%ld %ld\n"), from, to);
      }
      node = node->GetNext();
    }

    wxFprintf(Index, _T("}\n"));

    fclose(Contents); Contents = NULL;
    fclose(Chapters); Chapters = NULL;
    fclose(Sections); Sections = NULL;
    fclose(Subsections); Subsections = NULL;
    fclose(Subsubsections); Subsubsections = NULL;
    fclose(Index); Index = NULL;

    if (wxFileExists(ContentsName)) wxRemoveFile(ContentsName);

    if (!wxRenameFile(TmpContentsName, ContentsName))
    {
      wxCopyFile(TmpContentsName, ContentsName);
      wxRemoveFile(TmpContentsName);
    }

    wxConcatFiles(_T("chapters.xlp"), _T("sections.xlp"), _T("tmp2.xlp"));
    wxConcatFiles(_T("tmp2.xlp"), _T("subsections.xlp"), _T("tmp1.xlp"));
    wxConcatFiles(_T("tmp1.xlp"), _T("subsubsections.xlp"), _T("tmp2.xlp"));
    wxConcatFiles(_T("tmp2.xlp"), _T("index.xlp"), OutputFile);

    wxRemoveFile(_T("tmp1.xlp"));
    wxRemoveFile(_T("tmp2.xlp"));

    wxRemoveFile(_T("chapters.xlp"));
    wxRemoveFile(_T("sections.xlp"));
    wxRemoveFile(_T("subsections.xlp"));
    wxRemoveFile(_T("subsubsections.xlp"));
    wxRemoveFile(_T("index.xlp"));
    return true;
  }
  return false;
}
Пример #12
0
bool MyApp::OnInit()
{
  // MSW: Perhaps that is faster.
  wxSystemOptions::SetOption("msw.display.directdraw","1");
  // No spell checking in our dialog's input portions on the mac.
  wxSystemOptions::SetOption("mac.textcontrol-use-spell-checker","0");
  
  // Migrate an eventual old config file to the location XDG wants it to be.
  #ifndef __WXMSW__
  #if wxCHECK_VERSION(3, 1, 1)
  wxStandardPaths::Get().SetFileLayout(wxStandardPaths::FileLayout_Classic);
  wxString configFileOld = wxStandardPaths::Get().GetUserConfigDir() + wxT("/") +
    wxStandardPaths::Get().MakeConfigFileName(
      wxString(wxT("wxMaxima")),
      wxStandardPaths::ConfigFileConv_Dot);
  wxStandardPaths::Get().SetFileLayout(wxStandardPaths::FileLayout_XDG);
  wxString configFileXDG = wxStandardPaths::Get().GetUserConfigDir() + wxT("/") +
    wxStandardPaths::Get().MakeConfigFileName(
      wxString(wxT("wxMaxima")),
      wxStandardPaths::ConfigFileConv_Ext);

  if(!wxFileExists(configFileXDG))
  {
    wxFileName xdgDir(configFileXDG);
    wxString dirName(xdgDir.GetPath());
    if(!wxDirExists(dirName))
      wxMkDir(dirName,0x700);
    wxLogNull blocker;
    if(wxFileExists(configFileOld))
      wxCopyFile(configFileOld,configFileXDG);
  }
  #endif
  #endif

  wxConfig::Set(new wxFileConfig(wxT("wxMaxima"), wxEmptyString, m_configFileName));

  atexit(Cleanup);
  int lang = wxLANGUAGE_UNKNOWN;

  bool exitAfterEval = false;
  bool evalOnStartup = false;

  wxCmdLineParser cmdLineParser(argc, argv);

  static const wxCmdLineEntryDesc cmdLineDesc[] =
          {
            {wxCMD_LINE_SWITCH, "v", "version", "Output the version info", wxCMD_LINE_VAL_NONE , 0},
                  /* Usually wxCMD_LINE_OPTION_HELP is used with the following option, but that displays a message
                   * using a own window and we want the message on the command line. If a user enters a command
                   * line option, he expects probably a answer just on the command line... */
                  {wxCMD_LINE_SWITCH, "h", "help", "show this help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP},
                  {wxCMD_LINE_OPTION, "o", "open", "open a file", wxCMD_LINE_VAL_STRING , 0},
                  {wxCMD_LINE_SWITCH, "e", "eval",
                   "evaluate the file after opening it.", wxCMD_LINE_VAL_NONE , 0},
                  {wxCMD_LINE_SWITCH, "b", "batch",
                   "run the file and exit afterwards. Halts on questions and stops on errors.",  wxCMD_LINE_VAL_NONE, 0},
                  { wxCMD_LINE_OPTION, "f", "ini", "allows to specify a file to store the configuration in", wxCMD_LINE_VAL_STRING , 0},
                  { wxCMD_LINE_OPTION, "m", "maxima", "allows to specify the location of the maxima binary", wxCMD_LINE_VAL_STRING , 0},
                  {wxCMD_LINE_PARAM, NULL, NULL, "input file", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE},
            {wxCMD_LINE_NONE, "", "", "", wxCMD_LINE_VAL_NONE, 0}
          };

  cmdLineParser.SetDesc(cmdLineDesc);
  cmdLineParser.Parse();
  wxString ini, file;
  // Attention: The config file is changed by wxMaximaFrame::wxMaximaFrame::ReReadConfig
  if (cmdLineParser.Found(wxT("f"),&ini))
  {
    Configuration::m_maximaLocation_override = ini;
  }
  else
    wxConfig::Set(new wxConfig(wxT("wxMaxima")));

  if (cmdLineParser.Found(wxT("m"),&ini))
    wxConfig::Get()->Write(wxT("maxima"), ini);

  wxImage::AddHandler(new wxPNGHandler);
  wxImage::AddHandler(new wxXPMHandler);
  wxImage::AddHandler(new wxJPEGHandler);

  wxFileSystem::AddHandler(new wxZipFSHandler);

  wxConfigBase *config = wxConfig::Get();
  lang = wxLocale::GetSystemLanguage();
  config->Read(wxT("language"), &lang);

  if(wxLocale::IsAvailable(lang))
    m_locale.Init(lang);
  else
    m_locale.Init(wxLANGUAGE_ENGLISH);

  m_dirstruct =  new Dirstructure;
  if((lang != wxLANGUAGE_UNKNOWN) && (lang != wxLANGUAGE_DEFAULT) &&
     (lang != wxLocale::GetSystemLanguage()))
    wxSetEnv(wxT("LANG"), m_locale.GetCanonicalName());

#ifdef __WXMSW__
  wxString oldWorkingDir = wxGetCwd();
  if (!wxGetEnv(wxT("BUILD_DIR"), NULL))
  {
    wxString dir = wxPathOnly(wxStandardPaths::Get().GetExecutablePath());
    if(dir != wxEmptyString)
      wxSetWorkingDirectory(wxPathOnly(wxStandardPaths::Get().GetExecutablePath()));
  }
  wxString fontPrefix = m_dirstruct->FontDir() + wxT("/");  
  /* Add private jsMath fonts, if they exist */ 
#if wxCHECK_VERSION(3, 1, 1)
  if (wxFileExists(fontPrefix + wxT(CMEX10) + wxT(".ttf"))) wxFont::AddPrivateFont(fontPrefix + wxT(CMEX10) + wxT(".ttf"));
  if (wxFileExists(fontPrefix + wxT(CMSY10) + wxT(".ttf"))) wxFont::AddPrivateFont(fontPrefix + wxT(CMSY10) + wxT(".ttf"));
  if (wxFileExists(fontPrefix + wxT(CMR10) + wxT(".ttf")))  wxFont::AddPrivateFont(fontPrefix + wxT(CMR10) + wxT(".ttf"));
  if (wxFileExists(fontPrefix + wxT(CMMI10) + wxT(".ttf"))) wxFont::AddPrivateFont(fontPrefix + wxT(CMMI10) + wxT(".ttf"));
  if (wxFileExists(fontPrefix + wxT(CMTI10) + wxT(".ttf"))) wxFont::AddPrivateFont(fontPrefix + wxT(CMTI10) + wxT(".ttf"));

  /* Add private Libertine fonts, if they exist */
  if (wxFileExists(fontPrefix + wxT(LIBERTINE1))) 
	  wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE1));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE2))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE2));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE3))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE3));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE4))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE4));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE5))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE5));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE6))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE6));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE7))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE7));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE8))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE8));
  if (wxFileExists(fontPrefix + wxT(LIBERTINE9))) wxFont::AddPrivateFont(fontPrefix + wxT(LIBERTINE9));
#endif
  wxSetWorkingDirectory(oldWorkingDir);

#endif

  m_locale.AddCatalogLookupPathPrefix(m_dirstruct->LocaleDir());
  m_locale.AddCatalogLookupPathPrefix(m_dirstruct->LocaleDir()+wxT("/wxwin"));
  m_locale.AddCatalogLookupPathPrefix(wxT("/usr/share/locale"));
  m_locale.AddCatalogLookupPathPrefix(wxT("/usr/local/share/locale"));
  m_locale.AddCatalog(wxT("wxMaxima"));
  m_locale.AddCatalog(wxT("wxMaxima-wxstd"));

#if defined __WXMAC__
  wxString path;
  wxGetEnv(wxT("PATH"), &path);
  wxSetEnv(wxT("PATH"), path << wxT(":/usr/local/bin"));

  wxApp::SetExitOnFrameDelete(false);
  wxMenuBar *menuBar = new wxMenuBar;
  wxMenu *fileMenu = new wxMenu;
  fileMenu->Append(wxMaxima::mac_newId, _("&New\tCtrl+N"));
  fileMenu->Append(wxMaxima::mac_openId, _("&Open\tCtrl+O"));
  menuBar->Append(fileMenu, _("File"));
  wxMenuBar::MacSetCommonMenuBar(menuBar);

  Connect(wxMaxima::mac_newId, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyApp::OnFileMenu));
  Connect(wxMaxima::mac_openId, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyApp::OnFileMenu));
  Connect(wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyApp::OnFileMenu));
#endif

  if (cmdLineParser.Found(wxT("v")))
  {
    std::cout << "wxMaxima ";
    std::cout << GITVERSION;
#if defined(WXMAXIMA_GIT_VERSION)
    std::cout << " (Git version: " << WXMAXIMA_GIT_VERSION << ")";
#endif
    std::cout << "\n";
    wxExit();
  }
  if (cmdLineParser.Found(wxT("h")))
  {
    std::cout << "A feature-rich graphical user interface for the computer algebra system maxima\n";
    std::cout << cmdLineParser.GetUsageString();
    wxExit();
  }

  if (cmdLineParser.Found(wxT("b")))
  {
    evalOnStartup = true;
    exitAfterEval = true;
  }
  
  if (cmdLineParser.Found(wxT("e")))
    evalOnStartup = true;

  if (cmdLineParser.Found(wxT("o"), &file))
  {
    wxFileName FileName = file;
    FileName.MakeAbsolute();
    wxString CanonicalFilename = FileName.GetFullPath();
    NewWindow(wxString(CanonicalFilename), evalOnStartup, exitAfterEval);
    return true;
  }

  if(cmdLineParser.GetParamCount() > 0)
  {
    for (unsigned int i=0; i < cmdLineParser.GetParamCount(); i++)
    {
      wxFileName FileName = cmdLineParser.GetParam(i);
      FileName.MakeAbsolute();
      
      wxString CanonicalFilename = FileName.GetFullPath();
      NewWindow(CanonicalFilename, evalOnStartup, exitAfterEval);
    }
  }
  else
    NewWindow();

  return true;
}
Пример #13
0
void ModderTask::TaskStart()
{
    // Get the mod list
    const ModList *modList = m_inst->GetModList();

    wxFileName mcBin = m_inst->GetBinDir();
    wxFileName mcJar = m_inst->GetMCJar();
    wxFileName mcBackup = m_inst->GetMCBackup();

    SetStatus(_("Installing mods - backing up minecraft.jar..."));
    if (!mcBackup.FileExists() && !wxCopyFile(mcJar.GetFullPath(), mcBackup.GetFullPath()))
    {
        OnFail(_("Failed to back up minecraft.jar"));
        return;
    }

    if (mcJar.FileExists() && !wxRemoveFile(mcJar.GetFullPath()))
    {
        OnFail(_("Failed to delete old minecraft.jar"));
        return;
    }


    if (TestDestroy())
        return;
    TaskStep(); // STEP 1
    SetStatus(_("Installing mods - Opening minecraft.jar"));

    wxFFileOutputStream jarStream(mcJar.GetFullPath());
    wxZipOutputStream zipOut(jarStream);

    {
        wxFFileInputStream inStream(mcBackup.GetFullPath());
        wxZipInputStream zipIn(inStream);

        std::auto_ptr<wxZipEntry> entry;
        while (entry.reset(zipIn.GetNextEntry()), entry.get() != NULL)
            if (!entry->GetName().Matches(_("META-INF*")))
                if (!zipOut.CopyEntry(entry.release(), zipIn))
                    break;
    }

    // Modify the jar
    TaskStep(); // STEP 2
    SetStatus(_("Installing mods - Adding mod files..."));
    for (ConstModIterator iter = modList->begin(); iter != modList->end(); iter++)
    {
        wxFileName modFileName = iter->GetFileName();
        SetStatus(_("Installing mods - Adding ") + modFileName.GetFullName());
        if (iter->IsZipMod())
        {
            wxFFileInputStream modStream(modFileName.GetFullPath());
            TransferZipArchive(modStream, zipOut);
        }
        else
        {
            wxFileName destFileName = modFileName;
            destFileName.MakeRelativeTo(m_inst->GetInstModsDir().GetFullPath());

            wxFFileInputStream input(modFileName.GetFullPath());
            zipOut.PutNextEntry(destFileName.GetFullPath());
            zipOut.Write(input);
        }
    }

    // Recompress the jar
    TaskStep(); // STEP 3
    SetStatus(_("Installing mods - Recompressing jar..."));

    m_inst->SetNeedsRebuild(false);
}
Пример #14
0
static void export_vrml_module( BOARD* aPcb, MODULE* aModule,
                                FILE* aOutputFile,
                                double aVRMLModelsToBiu,
                                bool aExport3DFiles, const wxString & a3D_Subdir,
                                double boardIU2WRML )
{
    // Reference and value
    export_vrml_text_module( aModule->m_Reference );
    export_vrml_text_module( aModule->m_Value );

    // Export module edges
    for( EDA_ITEM* item = aModule->m_Drawings;  item != NULL;  item = item->Next() )
    {
        switch( item->Type() )
        {
        case PCB_MODULE_TEXT_T:
            export_vrml_text_module( dynamic_cast<TEXTE_MODULE*>(item) );
            break;

        case PCB_MODULE_EDGE_T:
            export_vrml_edge_module( dynamic_cast<EDGE_MODULE*>(item) );
            break;

        default:
            break;
        }
    }

    // Export pads
    for( D_PAD* pad = aModule->m_Pads;  pad; pad = pad->Next() )
        export_vrml_pad( aPcb, pad );

    bool isFlipped = aModule->GetLayer() == LAYER_N_BACK;

    // Export the object VRML model(s)
    for( S3D_MASTER* vrmlm = aModule->m_3D_Drawings; vrmlm != 0; vrmlm = vrmlm->Next() )
    {
        wxString fname = vrmlm->m_Shape3DName;

        if( fname.IsEmpty() )
            continue;

        if( ! wxFileName::FileExists( fname ) )
        {
            wxFileName fn = fname;
            fname = wxGetApp().FindLibraryPath( fn );

            if( fname.IsEmpty() )   // keep "short" name if full filemane not found
                fname = vrmlm->m_Shape3DName;
        }

        fname.Replace(wxT("\\"), wxT("/" ) );
        wxString source_fname = fname;

        if( aExport3DFiles )    // Change illegal characters in short filename
        {
            ChangeIllegalCharacters( fname, true );
            fname = a3D_Subdir + wxT("/") + fname;

            if( !wxFileExists( fname ) )
                wxCopyFile( source_fname, fname );
        }

        /* Calculate 3D shape rotation:
         * this is the rotation parameters, with an additional 180 deg rotation
         * for footprints that are flipped
         * When flipped, axis rotation is the horizontal axis (X axis)
         */
        double rotx = - vrmlm->m_MatRotation.x;
        double roty = - vrmlm->m_MatRotation.y;
        double rotz = - vrmlm->m_MatRotation.z;

        if ( isFlipped )
        {
            rotx += 180.0;
            NEGATE(roty);
            NEGATE(rotz);
        }

        // Do some quaternion munching
        double q1[4], q2[4], rot[4];
        build_quat( 1, 0, 0, rotx / 180.0 * M_PI, q1 );
        build_quat( 0, 1, 0, roty / 180.0 * M_PI, q2 );
        compose_quat( q1, q2, q1 );
        build_quat( 0, 0, 1, rotz / 180.0 * M_PI, q2 );
        compose_quat( q1, q2, q1 );
        // Note here aModule->GetOrientation() is in 0.1 degrees,
        // so module rotation is aModule->GetOrientation() / 1800.0
        build_quat( 0, 0, 1, aModule->GetOrientation() / 1800.0 * M_PI, q2 );
        compose_quat( q1, q2, q1 );
        from_quat( q1, rot );

        fprintf( aOutputFile, "Transform {\n" );
        // A null rotation would fail the acos!
        if( rot[3] != 0.0 )
        {
            fprintf( aOutputFile, "  rotation %g %g %g %g\n", rot[0], rot[1], rot[2], rot[3] );
        }

        // adjust 3D shape offset position
        int offsetx = vrmlm->m_MatPosition.x;
        int offsety = vrmlm->m_MatPosition.y;
        double offsetz = vrmlm->m_MatPosition.z;

        if ( isFlipped )
            NEGATE(offsetz);
        else    // In normal mode, Y axis is reversed in Pcbnew.
            NEGATE(offsety);

        RotatePoint(&offsetx, &offsety, aModule->GetOrientation());

        fprintf( aOutputFile, "  translation %g %g %g\n",
                 (double) (offsetx + aModule->m_Pos.x) * boardIU2WRML,
                 - (double)(offsety + aModule->m_Pos.y) * boardIU2WRML,    // Y axis is reversed in Pcbnew
                 offsetz + layer_z[aModule->GetLayer()] * boardIU2WRML);

        fprintf( aOutputFile, "  scale %g %g %g\n",
                 vrmlm->m_MatScale.x * aVRMLModelsToBiu,
                 vrmlm->m_MatScale.y * aVRMLModelsToBiu,
                 vrmlm->m_MatScale.z * aVRMLModelsToBiu );

        fprintf( aOutputFile,
//                 "  children [\n    Inline {\n      url \"file://%s\"\n    } ]\n",
                 "  children [\n    Inline {\n      url \"%s\"\n    } ]\n",
                 TO_UTF8( fname ) );
        fprintf( aOutputFile, "  }\n" );
    }
}
Пример #15
0
void TemplateManager::SaveUserTemplate(cbProject* prj)
{
    if (!prj)
        return;

    // save project & all files
    if (!prj->SaveAllFiles() ||
        !prj->Save())
    {
        cbMessageBox(_("Could not save project and/or all its files. Aborting..."), _("Error"), wxICON_ERROR);
        return;
    }

    // create destination dir
    wxString templ = ConfigManager::GetConfigFolder() + wxFILE_SEP_PATH + _T("UserTemplates");
    if (!CreateDirRecursively(templ, 0755))
    {
        cbMessageBox(_("Couldn't create directory for user templates:\n") + templ, _("Error"), wxICON_ERROR);
        return;
    }

    // check if it exists and ask a different title
    wxString title = prj->GetTitle();
    while (true)
    {
        // ask for template title (unique)
        wxTextEntryDialog dlg(0, _("Enter a title for this template"), _("Enter title"), title);
        PlaceWindow(&dlg);
        if (dlg.ShowModal() != wxID_OK)
            return;

        title = dlg.GetValue();
        if (!wxDirExists(templ + wxFILE_SEP_PATH + title))
        {
            templ << wxFILE_SEP_PATH << title;
            wxMkdir(templ, 0755);
            break;
        }
        else
            cbMessageBox(_("You have another template with the same title.\nPlease choose another title..."));
    }

    wxBusyCursor busy;

    // copy project and all files to destination dir
    int count = 0;
    int total_count = prj->GetFilesCount();
    templ << wxFILE_SEP_PATH;
    wxFileName fname;
    for (int i = 0; i < total_count; ++i)
    {
        wxString src = prj->GetFile(i)->file.GetFullPath();
        wxString dst = templ + prj->GetFile(i)->relativeToCommonTopLevelPath;
        #if wxCHECK_VERSION(2, 9, 0)
        Manager::Get()->GetLogManager()->DebugLog(F(_T("Copying %s to %s"), src.wx_str(), dst.wx_str()));
        #else
        Manager::Get()->GetLogManager()->DebugLog(F(_T("Copying %s to %s"), src.c_str(), dst.c_str()));
        #endif
        if (!CreateDirRecursively(dst))
            Manager::Get()->GetLogManager()->DebugLog(_T("Failed creating directory for ") + dst);
        if (wxCopyFile(src, dst, true))
            ++count;
        else
            #if wxCHECK_VERSION(2, 9, 0)
            Manager::Get()->GetLogManager()->DebugLog(F(_T("Failed copying %s to %s"), src.wx_str(), dst.wx_str()));
            #else
            Manager::Get()->GetLogManager()->DebugLog(F(_T("Failed copying %s to %s"), src.c_str(), dst.c_str()));
            #endif
    }

    // cbProject doesn't have a GetRelativeToCommonTopLevelPath() function, so we simulate it here
    // to find out the real destination file to create...
    wxString topLevelPath = prj->GetCommonTopLevelPath();
    fname.Assign(prj->GetFilename());
    fname.MakeRelativeTo(topLevelPath);
    fname.Assign(templ + fname.GetFullPath());
    if (!CreateDirRecursively(fname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR), 0755))
    {
        cbMessageBox(_("Failed to create the directory for the project file!"), _("Error"), wxICON_ERROR);
        ++count;
    }
    else
    {
        if (!wxCopyFile(prj->GetFilename(), fname.GetFullPath()))
        {
            Manager::Get()->GetLogManager()->DebugLog(_T("Failed to copy the project file: ") + fname.GetFullPath());
            cbMessageBox(_("Failed to copy the project file!"), _("Error"), wxICON_ERROR);
            ++count;
        }
    }

    if (count == total_count)
        cbMessageBox(_("User-template saved successfully"), _("Information"), wxICON_INFORMATION | wxOK);
    else
        cbMessageBox(_("Some files could not be saved with the template..."), _("Error"), wxICON_ERROR);
}
Пример #16
0
bool AppConfig::load() {
    DataTree cfg;
    std::string cfgFileDir = getConfigDir();

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

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

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

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

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

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

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

        // default:
        perfMode.store(PERF_NORMAL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


    return true;
}
Пример #17
0
wxThread::ExitCode ModderTask::TaskStart()
{
	// Get the mod list
	ModList *modList = m_inst->GetModList();
	
	wxFileName mcBin = m_inst->GetBinDir();
	wxFileName mcJar = m_inst->GetMCJar();
	wxFileName mcBackup = m_inst->GetMCBackup();
	
	// Nothing to do if there are no jar mods to install, no backup and just the mc jar
	if(mcJar.FileExists() && !mcBackup.FileExists() && modList->empty())
	{
		m_inst->SetNeedsRebuild(false);
		return (ExitCode)1;
	}
	
	SetStatus(_("Installing mods - backing up minecraft.jar..."));
	if (!mcBackup.FileExists() && !wxCopyFile(mcJar.GetFullPath(), mcBackup.GetFullPath()))
	{
		OnFail(_("Failed to back up minecraft.jar"));
		return (ExitCode)0;
	}
	
	if (mcJar.FileExists() && !wxRemoveFile(mcJar.GetFullPath()))
	{
		OnFail(_("Failed to delete old minecraft.jar"));
		return (ExitCode)0;
	}
	
	// TODO: good spot for user cancel check? or not...
	
	TaskStep(); // STEP 1
	SetStatus(_("Installing mods - Opening minecraft.jar"));

	wxFFileOutputStream jarStream(mcJar.GetFullPath());
	wxZipOutputStream zipOut(jarStream);

	// Files already added to the jar.
	// These files will be skipped.
	std::set<wxString> addedFiles;

	// Modify the jar
	TaskStep(); // STEP 2
	SetStatus(_("Installing mods - Adding mod files..."));
	for (ModList::const_reverse_iterator iter = modList->rbegin(); iter != modList->rend(); iter++)
	{
		wxFileName modFileName = iter->GetFileName();
		SetStatus(_("Installing mods - Adding ") + modFileName.GetFullName());
		if (iter->IsZipMod())
		{
			wxFFileInputStream modStream(modFileName.GetFullPath());
			wxZipInputStream zipStream(modStream);
			std::auto_ptr<wxZipEntry> entry;
			while (entry.reset(zipStream.GetNextEntry()), entry.get() != NULL)
			{
				if (entry->IsDir())
					continue;

				wxString name = entry->GetName();
				if (addedFiles.count(name) == 0)
				{
					if (!zipOut.CopyEntry(entry.release(), zipStream))
						break;
					addedFiles.insert(name);
				}
			}
		}
		else
		{
			wxFileName destFileName = modFileName;
			destFileName.MakeRelativeTo(m_inst->GetInstModsDir().GetFullPath());
			wxString destFile = destFileName.GetFullPath();

			if (addedFiles.count(destFile) == 0)
			{
				wxFFileInputStream input(modFileName.GetFullPath());
				zipOut.PutNextEntry(destFile);
				zipOut.Write(input);

				addedFiles.insert(destFile);
			}
		}
	}

	{
		wxFFileInputStream inStream(mcBackup.GetFullPath());
		wxZipInputStream zipIn(inStream);

		std::auto_ptr<wxZipEntry> entry;
		while (entry.reset(zipIn.GetNextEntry()), entry.get() != NULL)
		{
			wxString name = entry->GetName();

			if (!name.Matches("META-INF*") &&
				addedFiles.count(name) == 0)
			{
				if (!zipOut.CopyEntry(entry.release(), zipIn))
					break;
				addedFiles.insert(name);
			}
		}
	}
	
	// Recompress the jar
	TaskStep(); // STEP 3
	SetStatus(_("Installing mods - Recompressing jar..."));

	m_inst->SetNeedsRebuild(false);
	m_inst->UpdateVersion(true);
	return (ExitCode)1;
}
Пример #18
0
void Project::CopyTo(const wxString& new_path, const wxString& new_name, const wxString& description)
{
    // first save the xml document to the destination folder

    wxString newFile = new_path + new_name + wxT(".project");
    if ( !m_doc.Save( newFile ) ) {
        return;
    }

    // load the new xml and modify it
    wxXmlDocument doc;
    if ( !doc.Load( newFile ) ) {
        return;
    }

    // update the 'Name' property
    XmlUtils::UpdateProperty(doc.GetRoot(), wxT("Name"), new_name);

    // set description
    wxXmlNode *descNode(NULL);

    // update the description
    descNode = XmlUtils::FindFirstByTagName(doc.GetRoot(), wxT("Description"));
    if (!descNode) {
        descNode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Description"));
        doc.GetRoot()->AddChild(descNode);
    }
    XmlUtils::SetNodeContent(descNode, description);

    // Remove the 'Dependencies'
    wxXmlNode *deps = doc.GetRoot()->GetChildren();
    while(deps) {
        if(deps->GetName() == wxT("Dependencies")) {
            doc.GetRoot()->RemoveChild(deps);
            delete deps;

            // restart the search from the begining
            deps = doc.GetRoot()->GetChildren();

        } else {
            // try next child
            deps = deps->GetNext();
        }
    }

    // add an empty deps node
    deps = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Dependencies"));
    doc.GetRoot()->AddChild(deps);

    // Remove virtual folders
    wxXmlNode *vd = XmlUtils::FindFirstByTagName(doc.GetRoot(), wxT("VirtualDirectory"));
    while (vd) {
        doc.GetRoot()->RemoveChild( vd );
        delete vd;
        vd = XmlUtils::FindFirstByTagName(doc.GetRoot(), wxT("VirtualDirectory"));
    }

    // add all files under this path
    std::vector<wxFileName> files;
    GetFiles(files, true);

    wxXmlNode *srcNode(NULL);
    wxXmlNode *headNode(NULL);
    wxXmlNode *rcNode(NULL);

    // copy the files to their new location
    for (size_t i=0; i<files.size(); i++) {
        wxFileName fn = files.at(i);
        wxCopyFile(fn.GetFullPath(), new_path + wxT("/") + fn.GetFullName());

        wxXmlNode *file_node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("File"));
        file_node->AddProperty(wxT("Name"), fn.GetFullName());

        switch ( FileExtManager::GetType( fn.GetFullName() ) ) {
        case FileExtManager::TypeSourceC:
        case FileExtManager::TypeSourceCpp:

            // source file
            if ( !srcNode ) {
                srcNode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("VirtualDirectory"));
                srcNode->AddProperty(wxT("Name"), wxT("src"));
                doc.GetRoot()->AddChild(srcNode);
            }
            srcNode->AddChild(file_node);
            break;

        case FileExtManager::TypeHeader:
            // header file
            if (!headNode) {
                headNode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("VirtualDirectory"));
                headNode->AddProperty(wxT("Name"), wxT("include"));
                doc.GetRoot()->AddChild(headNode);
            }
            headNode->AddChild(file_node);
            break;

        default:
            // resource file
            if ( !rcNode ) {
                rcNode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("VirtualDirectory"));
                rcNode->AddProperty(wxT("Name"), wxT("resources"));
                doc.GetRoot()->AddChild(rcNode);
            }
            rcNode->AddChild(file_node);
            break;
        }
    }

    doc.Save(newFile);
}
Пример #19
0
void wxFormBuilder::DoCreateWxFormBuilderProject(const wxFBItemInfo& data)
{
	// add new virtual folder to the selected virtual directory
	wxString formbuilderVD;
	formbuilderVD = data.virtualFolder.BeforeFirst(wxT(':'));

	m_mgr->CreateGroupFolder(formbuilderVD, wxT("formbuilder"));
	wxString templateFile(m_mgr->GetInstallDirectory() + wxT("/templates/formbuilder/"));     //todo,todo

	switch (data.kind) {
	default:
	case wxFBItemKind_Dialog:
		templateFile << wxT("DialogTemplate.fbp");
		break;
	case wxFBItemKind_Frame:
		templateFile << wxT("FrameTemplate.fbp");
		break;
	case wxFBItemKind_Panel:
		templateFile << wxT("PanelTemplate.fbp");
		break;
	case wxFBItemKind_Dialog_With_Buttons:
		templateFile << wxT("DialogTemplateWithButtons.fbp");
		break;
	}

	wxFileName tmplFile(templateFile);
	if (!tmplFile.FileExists()) {
		wxMessageBox(wxString::Format(wxT("Cant find wxFormBuilder template file '%s'"), tmplFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
		return;
	}

	// place the files under the VD's project owner
	wxString err_msg;
	wxString project = data.virtualFolder.BeforeFirst(wxT(':'));
	ProjectPtr proj = m_mgr->GetSolution()->FindProjectByName(project, err_msg);
	if (proj) {
		wxString files_path = proj->GetFileName().GetPath(wxPATH_GET_SEPARATOR|wxPATH_GET_VOLUME);
		// copy the file to here
		wxFileName fbpFile(files_path, data.file + wxT(".fbp"));
		if (!wxCopyFile(tmplFile.GetFullPath(), fbpFile.GetFullPath())) {
			wxMessageBox(wxString::Format(wxT("Failed to copy tempalte file to '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}
		// open the file, and replace expand its macros
		wxString content;
		if (!ReadFileWithConversion(fbpFile.GetFullPath().c_str(), content)) {
			wxMessageBox(wxString::Format(wxT("Failed to read file '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}

		content.Replace(wxT("$(BaseFileName)"), data.file);
		content.Replace(wxT("$(ProjectName)"), data.className);
		content.Replace(wxT("$(Title)"), data.title);
		content.Replace(wxT("$(ClassName)"), data.className);

		if (!WriteFileWithBackup(fbpFile.GetFullPath().c_str(), content, false)) {
			wxMessageBox(wxString::Format(wxT("Failed to write file '%s'"), fbpFile.GetFullPath().c_str()), wxT("EmbeddedLite"), wxOK|wxCENTER|wxICON_WARNING);
			return;
		}

		// add the file to the project
		wxArrayString paths;
		paths.Add(fbpFile.GetFullPath());
		m_mgr->AddFilesToGroupFolder(project + wxT(":formbuilder"), paths);

		// // first we launch wxFB with the -g flag set
		wxString genFileCmd;
		genFileCmd << GetWxFBPath() << wxT(" -g ") << fbpFile.GetFullPath();

		wxArrayString dummy, filesToAdd;
		ProcUtils::SafeExecuteCommand(genFileCmd, dummy);

		wxFileName cppFile(fbpFile.GetPath(), data.file + wxT(".cpp"));
		wxFileName headerFile(fbpFile.GetPath(), data.file + wxT(".h"));

		if (cppFile.FileExists()) {
			filesToAdd.Add(cppFile.GetFullPath());
		}

		if (headerFile.FileExists()) {
			filesToAdd.Add(headerFile.GetFullPath());
		}

		if (filesToAdd.GetCount()) {
			m_mgr->AddFilesToGroupFolder(data.virtualFolder, filesToAdd);
		}

		DoLaunchWxFB(fbpFile.GetFullPath());
	}
}
Пример #20
0
void CState::HandleDroppedFiles(const wxFileDataObject* pFileDataObject, const CLocalPath& path, bool copy)
{
	const wxArrayString &files = pFileDataObject->GetFilenames();
	if (!files.Count())
		return;

#ifdef __WXMSW__
	int len = 1;

	for (unsigned int i = 0; i < files.Count(); i++)
		len += files[i].Len() + 1;

	// SHFILEOPSTRUCT's pTo and pFrom accept null-terminated lists
	// of null-terminated filenames.
	wxChar* from = new wxChar[len];
	wxChar* p = from;
	for (unsigned int i = 0; i < files.Count(); i++)
	{
		wxStrcpy(p, files[i]);
		p += files[i].Len() + 1;
	}
	*p = 0; // End of list

	wxChar* to = new wxChar[path.GetPath().Len() + 2];
	wxStrcpy(to, path.GetPath());
	to[path.GetPath().Len() + 1] = 0; // End of list

	SHFILEOPSTRUCT op = {0};
	op.pFrom = from;
	op.pTo = to;
	op.wFunc = copy ? FO_COPY : FO_MOVE;
	op.hwnd = (HWND)m_pMainFrame->GetHandle();
	SHFileOperation(&op);

	delete [] to;
	delete [] from;
#else
	for (unsigned int i = 0; i < files.Count(); i++)
	{
		const wxString& file(files[i]);

		wxLongLong size;
		bool is_link;
		CLocalFileSystem::local_fileType type = CLocalFileSystem::GetFileInfo(file, is_link, &size, 0, 0);
		if (type == CLocalFileSystem::file)
		{
			wxString name;
			CLocalPath sourcePath(file, &name);
			if (name.empty())
				continue;
			if (copy)
				wxCopyFile(file, path.GetPath() + name);
			else
				wxRenameFile(file, path.GetPath() + name);
		}
		else if (type == CLocalFileSystem::dir)
		{
			if (copy)
				RecursiveCopy(CLocalPath(file), path);
			else
			{
				CLocalPath sourcePath(file);
				if (!sourcePath.HasParent())
					continue;
				wxRenameFile(file, path.GetPath() + sourcePath.GetLastSegment());
			}
		}
	}
#endif

	RefreshLocal();
}
Пример #21
0
void MyDialog::OnButton_GA(wxCommandEvent& event )
{
	wxString aid=assemblyid->GetValue();
	if (aid.IsEmpty()) 
	{
		wxLogMessage("Sorry, you have to specify an AssemblyID !");
	} else {
	wxFileDialog* file_dialog=new wxFileDialog(this,"Save AssemblyPackage as...","","","*.zip",wxSAVE,wxDefaultPosition);
	int t=file_dialog->ShowModal();
	
	wxString file;
	wxString path;
	wxString filename;
	if (t==wxID_OK) {
		
		file=file_dialog->GetPath();
		path=file_dialog->GetDirectory();
		filename=file_dialog->GetFilename();
		
		wxString current_directory=wxGetCwd();
		std::vector <AComponentTreeCtrl::fileinfo> filelist=a_TreeCtrl->getFiles();

		std::vector <AComponentTreeCtrl::fileinfo> ::iterator iter;
		for(iter = filelist.begin(); 
		iter != filelist.end(); 
			iter++)
			{
				AComponentTreeCtrl::fileinfo finfo=(*iter);
				
				if (!(wxDirExists("tempqxml"))) 
				{
					wxMkdir("tempqxml");
				}
				//wxSetWorkingDirectory(current_directory.Append("tempqxml"));

				wxString temp="tempqxml/";
				
				wxCopyFile(finfo.link,temp.Append(finfo.filename), TRUE);

				
			}

			if (!(wxDirExists("tempqxml/meta-inf")))
			{
					wxMkdir("tempqxml/meta-inf");
			}
			
			// copy the instantiation properties fillearchives
			p_TreeCtrl->copy_filearchive("tempqxml/meta-inf");

			wxString cadfile="tempqxml/meta-inf/";
			cadfile.Append(filename);
			cadfile.Replace(".zip",".cad",TRUE);

			wxFile* outputfile = new wxFile(cadfile,wxFile::write);
			outputfile->Write(getOutputText().c_str(),wxConvLibc);
			outputfile->Close();

			wxString newDirectory=current_directory;
			newDirectory.Append("\\");
			newDirectory.Append("tempqxml");
			wxSetWorkingDirectory(newDirectory);
						
			//bool value;
			wxProcess *process = new wxProcess(this);
					
			wxString cmd = "zip -u  ";
			cmd.append(filename);
			cmd.append(" ");
			cmd.append("*.*");
	
			std::cout << cmd.c_str() << std::endl;
	
			wxExecute(cmd, wxEXEC_SYNC, NULL);
			cadfile.Replace("tempqxml/","",TRUE);
			wxString cmd2 = "zip -u ";
			cmd2.append(filename);
			cmd2.append(" ");
			cmd2.append("meta-inf/*.*");
			
			wxExecute(cmd2, wxEXEC_SYNC, NULL);
			delete process;
			
			wxCopyFile(filename,file, TRUE);
			
			wxRemoveFile(filename);

			for(iter = filelist.begin(); 
			iter != filelist.end(); 
			iter++)
			{
				AComponentTreeCtrl::fileinfo finfo=(*iter);
				
				wxRemoveFile(finfo.filename);
								
			}

			p_TreeCtrl->remove_files();
			wxRemoveFile(cadfile);
			wxRmdir("meta-inf");

			
			
	}

	file_dialog->~wxFileDialog();
	}
}
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;
}
Пример #23
0
void read_mse1_card(Set& set, wxFileInputStream& f, wxTextInputStream& file) {
	CardP card(new Card(*set.game));
	while (!f.Eof()) {
		// read a line
		String line = file.ReadLine();
		if (line.empty()) continue;
		Char type = line.GetChar(0);
		line = line.substr(1);
		// interpret this line
		switch (type) {
			case 'A': {		// done
				set.cards.push_back(card);
				return;
			} case 'B': {	// name
				card->value(_("name")) = to_script(line);
				break;
			} case 'C': case 'D': { // image filename
				LocalFileName image_file = set.newFileName(_("image"),_("")); // a new unique name in the package
				if (wxCopyFile(line, set.nameOut(image_file), true)) {
					card->value(_("image")) = script_local_image_file(image_file);
				}
				break;
			} case 'E':	{	// super type
				card->value(_("super type")) = to_script(line);
				break;
			} case 'F': {	// sub type
				card->value(_("sub type")) = to_script(line);
				break;
			} case 'G': {	// casting cost
				card->value(_("casting cost")) = to_script(line);
				break;
			} case 'H': {	// rarity
				String rarity;
				if      (line == _("(U)")) rarity = _("uncommon");
				else if (line == _("(R)")) rarity = _("rare");
				else                       rarity = _("common");
				card->value(_("rarity")) = to_script(rarity);
				break;
			} case 'I': {	// power/thoughness
				size_t pos = line.find_first_of(_('/'));
				if (pos != String::npos) {
					card->value(_("power")) = to_script(line.substr(0, pos));
					card->value(_("toughness")) = to_script(line.substr(pos+1));
				}
				break;
			} case 'J': {	// rule text or part of text
				append_line(card->value(_("rule text")), line);
				break;
			} case 'K':	{	// flavor text or part of text
				append_line(card->value(_("flavor text")), line);
				break;
			} case 'L': {	// card color (if not default)
				// decode color
				String color;
				if      (line == _("1")) color = _("white");
				else if (line == _("2")) color = _("blue");
				else if (line == _("3")) color = _("black");
				else if (line == _("4")) color = _("red");
				else if (line == _("5")) color = _("green");
				else if (line == _("6")) color = _("colorless");
				else if (line == _("7")) color = _("land");
				else if (line == _("9")) color = _("multicolor");
				else                     color = _("colorless");
				card->value(_("card color")) = to_script(color);
				break;
			} default: {
				throw ParseError(_("Not a valid MSE1 file"));
			}
		}
	}
}
static void export_vrml_module( MODEL_VRML& aModel, BOARD* aPcb, MODULE* aModule,
                                std::ofstream& aOutputFile, double aVRMLModelsToBiu,
                                bool aExport3DFiles, bool aUseRelativePaths,
                                const wxString& a3D_Subdir )
{
    // Reference and value
    if( aModule->Reference().IsVisible() )
        export_vrml_text_module( &aModule->Reference() );

    if( aModule->Value().IsVisible() )
        export_vrml_text_module( &aModule->Value() );

    // Export module edges
    for( EDA_ITEM* item = aModule->GraphicalItems(); item; item = item->Next() )
    {
        switch( item->Type() )
        {
        case PCB_MODULE_TEXT_T:
            export_vrml_text_module( static_cast<TEXTE_MODULE*>( item ) );
            break;

        case PCB_MODULE_EDGE_T:
            export_vrml_edge_module( aModel, static_cast<EDGE_MODULE*>( item ),
                                     aModule->GetOrientation() );
            break;

        default:
            break;
        }
    }

    // Export pads
    for( D_PAD* pad = aModule->Pads(); pad; pad = pad->Next() )
        export_vrml_pad( aModel, aPcb, pad );

    bool isFlipped = aModule->GetLayer() == B_Cu;

    // Export the object VRML model(s)
    for( S3D_MASTER* vrmlm = aModule->Models();  vrmlm;  vrmlm = vrmlm->Next() )
    {
        if( !vrmlm->Is3DType( S3D_MASTER::FILE3D_VRML ) )
            continue;

        wxFileName modelFileName = vrmlm->GetShape3DFullFilename();
        wxFileName destFileName( a3D_Subdir, modelFileName.GetName(), modelFileName.GetExt() );

        // Only copy VRML files.
        if( modelFileName.FileExists() && modelFileName.GetExt() == wxT( "wrl" ) )
        {
            if( aExport3DFiles )
            {
                wxDateTime srcModTime = modelFileName.GetModificationTime();
                wxDateTime destModTime = srcModTime;

                destModTime.SetToCurrent();

                if( destFileName.FileExists() )
                    destModTime = destFileName.GetModificationTime();

                // Only copy the file if it doesn't exist or has been modified.  This eliminates
                // the redundant file copies.
                if( srcModTime != destModTime )
                {
                    wxLogDebug( wxT( "Copying 3D model %s to %s." ),
                                GetChars( modelFileName.GetFullPath() ),
                                GetChars( destFileName.GetFullPath() ) );

                    if( !wxCopyFile( modelFileName.GetFullPath(), destFileName.GetFullPath() ) )
                        continue;
                }
            }

            /* Calculate 3D shape rotation:
             * this is the rotation parameters, with an additional 180 deg rotation
             * for footprints that are flipped
             * When flipped, axis rotation is the horizontal axis (X axis)
             */
            double rotx = -vrmlm->m_MatRotation.x;
            double roty = -vrmlm->m_MatRotation.y;
            double rotz = -vrmlm->m_MatRotation.z;

            if( isFlipped )
            {
                rotx += 180.0;
                NEGATE( roty );
                NEGATE( rotz );
            }

            // Do some quaternion munching
            double q1[4], q2[4], rot[4];
            build_quat( 1, 0, 0, DEG2RAD( rotx ), q1 );
            build_quat( 0, 1, 0, DEG2RAD( roty ), q2 );
            compose_quat( q1, q2, q1 );
            build_quat( 0, 0, 1, DEG2RAD( rotz ), q2 );
            compose_quat( q1, q2, q1 );

            // Note here aModule->GetOrientation() is in 0.1 degrees,
            // so module rotation has to be converted to radians
            build_quat( 0, 0, 1, DECIDEG2RAD( aModule->GetOrientation() ), q2 );
            compose_quat( q1, q2, q1 );
            from_quat( q1, rot );

            aOutputFile << "Transform {\n";

            // A null rotation would fail the acos!
            if( rot[3] != 0.0 )
            {
                aOutputFile << "  rotation " << std::setprecision( 3 );
                aOutputFile << rot[0] << " " << rot[1] << " " << rot[2] << " " << rot[3] << "\n";
            }

            // adjust 3D shape local offset position
            // they are given in inch, so they are converted in board IU.
            double offsetx = vrmlm->m_MatPosition.x * IU_PER_MILS * 1000.0;
            double offsety = vrmlm->m_MatPosition.y * IU_PER_MILS * 1000.0;
            double offsetz = vrmlm->m_MatPosition.z * IU_PER_MILS * 1000.0;

            if( isFlipped )
                NEGATE( offsetz );
            else // In normal mode, Y axis is reversed in Pcbnew.
                NEGATE( offsety );

            RotatePoint( &offsetx, &offsety, aModule->GetOrientation() );

            aOutputFile << "  translation " << std::setprecision( aModel.precision );
            aOutputFile << ( ( offsetx + aModule->GetPosition().x ) *
                             aModel.scale + aModel.tx ) << " ";
            aOutputFile << ( -(offsety + aModule->GetPosition().y) *
                             aModel.scale - aModel.ty ) << " ";
            aOutputFile << ( (offsetz * aModel.scale ) +
                             aModel.GetLayerZ( aModule->GetLayer() ) ) << "\n";
            aOutputFile << "  scale ";
            aOutputFile << ( vrmlm->m_MatScale.x * aVRMLModelsToBiu ) << " ";
            aOutputFile << ( vrmlm->m_MatScale.y * aVRMLModelsToBiu ) << " ";
            aOutputFile << ( vrmlm->m_MatScale.z * aVRMLModelsToBiu ) << "\n";
            aOutputFile << "  children [\n    Inline {\n      url \"";

            if( aUseRelativePaths )
            {
                wxFileName tmp = destFileName;
                tmp.SetExt( wxT( "" ) );
                tmp.SetName( wxT( "" ) );
                tmp.RemoveLastDir();
                destFileName.MakeRelativeTo( tmp.GetPath() );
            }

            wxString fn = destFileName.GetFullPath();
            fn.Replace( wxT( "\\" ), wxT( "/" ) );
            aOutputFile << TO_UTF8( fn ) << "\"\n    } ]\n";
            aOutputFile << "  }\n";
        }
    }
}
Пример #25
0
void CState::HandleDroppedFiles(const wxFileDataObject* pFileDataObject, wxString path, bool copy)
{
	if (path.Last() != wxFileName::GetPathSeparator())
		path += wxFileName::GetPathSeparator();

	const wxArrayString &files = pFileDataObject->GetFilenames();
	if (!files.Count())
		return;

#ifdef __WXMSW__
	int len = 1;

	for (unsigned int i = 0; i < files.Count(); i++)
		len += files[i].Len() + 1;

	wxChar* from = new wxChar[len];
	wxChar* p = from;
	for (unsigned int i = 0; i < files.Count(); i++)
	{
		wxStrcpy(p, files[i]);
		p += files[i].Len() + 1;
	}
	*p = 0;

	wxChar* to = new wxChar[path.Len() + 2];
	wxStrcpy(to, path);
	to[path.Len() + 1] = 0;

	SHFILEOPSTRUCT op = {0};
	op.pFrom = from;
	op.pTo = to;
	op.wFunc = copy ? FO_COPY : FO_MOVE;
	op.hwnd = (HWND)m_pMainFrame->GetHandle();
	SHFileOperation(&op);

	delete [] to;
	delete [] from;
#else
	for (unsigned int i = 0; i < files.Count(); i++)
	{
		const wxString& file = files[i];
		if (wxFile::Exists(file))
		{
			int pos = file.Find(wxFileName::GetPathSeparator(), true);
			if (pos == -1 || pos == (int)file.Len() - 1)
				continue;
			const wxString& name = file.Mid(pos + 1);
			if (copy)
				wxCopyFile(file, path + name);
			else
				wxRenameFile(file, path + name);
		}
		else if (wxDir::Exists(file))
		{
			if (copy)
				RecursiveCopy(file, path);
			else
			{
				int pos = file.Find(wxFileName::GetPathSeparator(), true);
				if (pos == -1 || pos == (int)file.Len() - 1)
					continue;
				const wxString& name = file.Mid(pos + 1);
				wxRenameFile(file, path + name);
			}
		}
	}
#endif

	RefreshLocal();
}
Пример #26
0
/*
What could be improved here:
-Option to prepend a numerical value to the destination filename to maintain 
the same order as the playlist
-Option to create a directory in the destination directory based on playlist name

SiW
*/
void MusikApp::CopyFiles(const CMusikSongArray &songs)
{
	//--------------------------------//
	//--- first choose a directory ---//
	//--------------------------------//
	wxFileName destdir;
	wxDirDialog dirdlg( g_MusikFrame, _("Please choose location to copy songs to:"), wxT(""), wxDD_NEW_DIR_BUTTON );
	if ( dirdlg.ShowModal() == wxID_OK )
		destdir.AssignDir(dirdlg.GetPath());
	else
		return;
	wxLongLong llFree;
	wxGetDiskSpace(destdir.GetFullPath(),NULL,&llFree);
	wxLongLong llNeeded =  GetTotalFilesize(songs);
	if(llFree  < llNeeded)
	{
		wxLongLong_t  ToLessBytes = llNeeded.GetValue() - llFree.GetValue();
		wxString  sToLessBytes = wxString::Format(wxT("%")wxLongLongFmtSpec wxT("d"), ToLessBytes);
		// not enough free space
		wxString errmsg = wxString::Format(_("There is not enough free space in directory \"%s\". You need %s bytes more free. Continue nevertheless?"),(const wxChar *)destdir.GetFullPath(),(const wxChar *)sToLessBytes);
		if(wxMessageBox(errmsg,	_("File copy warning"),wxYES|wxNO|wxCENTER|wxICON_EXCLAMATION ) == wxNO)
		{
			return;
		}
	}


	//-----------------------------------------------------//
	//--- now just loop through the files and copy them ---//
	//-----------------------------------------------------//

	wxProgressDialog dialog(_T("Copy files dialog"),
		_T("An informative message"),
		100,    // range
		g_MusikFrame,   // parent
		wxPD_CAN_ABORT |
		wxPD_APP_MODAL |
		// wxPD_AUTO_HIDE | -- try this as well
		wxPD_ELAPSED_TIME |
		wxPD_ESTIMATED_TIME |
		wxPD_REMAINING_TIME);

	wxLongLong llRemaining = llNeeded;

	for ( size_t n = 0; n < songs.GetCount(); n++ )
	{
		const wxFileName & sourcename = songs[n].MetaData.Filename;
		wxFileName destname( sourcename );
		destname.SetPath(destdir.GetPath(0));   // GetPath(0) because the default is GetPath(int flags = wxPATH_GET_VOLUME,
		destname.SetVolume(destdir.GetVolume());	  // i do it this complicated way, because wxFileName::SetPath() is buggy, as it does not handle the volume of path
		wxLongLong llPercent = ((llNeeded - llRemaining) * wxLL(100) /llNeeded );
		
		if(!dialog.Update(llPercent.ToLong(),wxString::Format(_("copying %s"),(const wxChar *)sourcename.GetFullPath())))
		{
			break;
		}
		if(!wxCopyFile( sourcename.GetFullPath(), destname.GetFullPath()))
		{

			wxString errmsg = wxString::Format(_("Failed to copy file %s. Continue?"),(const wxChar *)sourcename.GetFullPath());
			if(wxMessageBox(errmsg,	_("File copy error"),wxYES|wxNO|wxCENTER|wxICON_ERROR ) == wxNO)
				break;
		}
		llRemaining -= songs[n].MetaData.nFilesize;
	}
	dialog.Update(99,wxT(""));	// this is needed to make the gauge fill the whole area.
	dialog.Update(100,wxT(""));

}
Пример #27
0
bool wxDiagram::SaveFile(const wxString& filename)
{
  wxBeginBusyCursor();

  wxExprDatabase *database = new wxExprDatabase;

  // First write the diagram type
  wxExpr *header = new wxExpr(_T("diagram"));
  OnHeaderSave(*database, *header);

  database->Append(header);

  wxNode *node = m_shapeList->GetFirst();
  while (node)
  {
    wxShape *shape = (wxShape *)node->GetData();

    if (!shape->IsKindOf(CLASSINFO(wxControlPoint)))
    {
      wxExpr *expr;
      if (shape->IsKindOf(CLASSINFO(wxLineShape)))
        expr = new wxExpr(_T("line"));
       else
        expr = new wxExpr(_T("shape"));

      OnShapeSave(*database, *shape, *expr);
    }
    node = node->GetNext();
  }
  OnDatabaseSave(*database);

  wxString tempFile;
  wxGetTempFileName(wxT("diag"), tempFile);
  FILE* file = fopen(tempFile.mb_str(wxConvFile), "w");
  if (! file)
  {
    wxEndBusyCursor();
    delete database;
    return false;
  }

  database->Write(file);
  fclose(file);
  delete database;

/*
  // Save backup
  if (FileExists(filename))
  {
    char buf[400];
#ifdef __X__
    sprintf(buf, "%s.bak", filename);
#endif
#ifdef __WXMSW__
    sprintf(buf, "_diagram.bak");
#endif
    if (FileExists(buf)) wxRemoveFile(buf);
    if (!wxRenameFile(filename, buf))
    {
      wxCopyFile(filename, buf);
      wxRemoveFile(filename);
    }
  }
*/

  // Copy the temporary file to the correct filename
  if (!wxRenameFile(tempFile, filename))
  {
    wxCopyFile(tempFile, filename);
    wxRemoveFile(tempFile);
  }

  wxEndBusyCursor();
  return true;
}