Ejemplo n.º 1
0
FilePath FilePath::FromAbsoluteWx(const wxFileName& wxFn){
  assert(wxFn.IsAbsolute());
  assert(!wxFn.IsDir());
  return FilePath(new PathImpl(wxFn));
}
Ejemplo n.º 2
0
void PluginManager::AddWorkspaceToRecentlyUsedList(const wxFileName& filename)
{
    if(filename.Exists()) {
        ManagerST::Get()->AddToRecentlyOpenedWorkspaces(filename.GetFullPath());
    }
}
Ejemplo n.º 3
0
bool
header_editor_frame_c::open_file(wxFileName file_name) {
    if (!kax_analyzer_c::probe(wxMB(file_name.GetFullPath()))) {
        wxMessageBox(Z("The file you tried to open is not a Matroska file."), Z("Wrong file selected"), wxOK | wxCENTER | wxICON_ERROR);
        return false;
    }

    m_e_segment_info.reset();
    m_e_tracks.reset();

    m_analyzer = wx_kax_analyzer_cptr(new wx_kax_analyzer_c(this, wxMB(file_name.GetFullPath())));

    if (!m_analyzer->process(kax_analyzer_c::parse_mode_fast)) {
        wxMessageBox(Z("This file could not be opened or parsed."), Z("File parsing failed"), wxOK | wxCENTER | wxICON_ERROR);
        m_analyzer.reset();

        return false;
    }

    m_file_name = file_name;
    m_file_name.GetTimes(nullptr, &m_file_mtime, nullptr);

    set_window_title();

    m_ignore_tree_selection_changes = true;

    enable_menu_entries();

    m_bs_main->Hide(m_tc_tree);

    for (auto &page : m_pages)
        if (page->IsShown())
            page->Hide();

    m_tc_tree->DeleteChildren(m_root_id);
    m_bs_page->Clear();
    m_pages.clear();
    m_top_level_pages.clear();

    for (auto &data : m_analyzer->m_data)
        if (data->m_id == KaxInfo::ClassInfos.GlobalId) {
            handle_segment_info(data.get());
            break;
        }

    for (auto &data : m_analyzer->m_data)
        if (data->m_id == KaxTracks::ClassInfos.GlobalId) {
            handle_tracks(data.get());
            break;
        }

    m_analyzer->close_file();

    m_bs_main->Show(m_tc_tree);
    m_bs_main->Layout();

    last_open_dir                   = file_name.GetPath();

    m_ignore_tree_selection_changes = false;

    return true;
}
bool wxFileSystemWatcherBase::RemoveTree(const wxFileName& path)
{
    if (!path.DirExists())
        return false;

    // OPT could be optimised if we stored information about relationships
    // between paths
    class RemoveTraverser : public wxDirTraverser
    {
    public:
        RemoveTraverser(wxFileSystemWatcherBase* watcher,
                        const wxString& filespec) :
            m_watcher(watcher), m_filespec(filespec)
        {
        }

        virtual wxDirTraverseResult OnFile(const wxString& WXUNUSED(filename))
        {
            // We never watch the individual files when watching the tree, so
            // nothing to do here.
            return wxDIR_CONTINUE;
        }

        virtual wxDirTraverseResult OnDir(const wxString& dirname)
        {
            m_watcher->Remove(wxFileName::DirName(dirname));
            return wxDIR_CONTINUE;
        }

    private:
        wxFileSystemWatcherBase* m_watcher;
        wxString m_filespec;
    };

    // If AddTree() used a filespec, we must use the same one
    wxString canonical = GetCanonicalPath(path);
    wxFSWatchInfoMap::iterator it = m_watches.find(canonical);
    wxCHECK_MSG( it != m_watches.end(), false,
                 wxString::Format("Path '%s' is not watched", canonical) );
    wxFSWatchInfo watch = it->second;
    const wxString filespec = watch.GetFilespec();

#if defined(__WINDOWS__)
    // When there's no filespec, the wxMSW AddTree() would have set a watch
    // on only the passed 'path'. We must therefore remove only this
    if (filespec.empty())
    {
        return Remove(path);
    }
    // Otherwise fall through to the generic implementation
#endif // __WINDOWS__

    wxDir dir(path.GetFullPath());
    // AddTree() might have used the wxDIR_NO_FOLLOW to prevent asserts or
    // infinite loops in trees containing symlinks. We need to do the same
    // or we'll try to remove unwatched items. Let's hope the caller used
    // the same ShouldFollowLink() setting as in AddTree()...
    int flags = wxDIR_DIRS;
    if ( !path.ShouldFollowLink() )
    {
        flags |= wxDIR_NO_FOLLOW;
    }
    RemoveTraverser traverser(this, filespec);
    dir.Traverse(traverser, filespec, flags);

    // As in AddTree() above, handle the path itself explicitly.
    Remove(path);

    return true;
}
Ejemplo n.º 5
0
/** DoLoadFile
  *
  * Handles loading an assembly file into the simulator
  */
void ComplxFrame::DoLoadFile(const wxFileName& filename)
{
    //CleanUp();
    lc3_state dummy_state;
    lc3_init(dummy_state);

    // Save the symbols
    std::map<std::string, unsigned short> symbol_table = state.symbols;
    std::map<unsigned short, std::string> rev_symbol_table = state.rev_symbols;

    state.symbols.clear();
    state.rev_symbols.clear();
    lc3_remove_plugins(state);

    try
    {
        std::vector<code_range> ranges;
        lc3_assemble(dummy_state, filename.GetFullPath().ToStdString(), false);
        lc3_assemble(state, filename.GetFullPath().ToStdString(), ranges);
        modified_addresses.clear();
        for (const auto& code_range : ranges)
            modified_addresses.push_back(ViewRange(code_range.location, code_range.location + code_range.size));
        // Dummy call to update hidden addresses.
        wxCommandEvent event;
        OnUpdateHideAddresses(event);
    }
    catch (LC3AssembleException e)
    {
        wxMessageBox(wxString::Format("BAD STUDENT! %s", e.what()), _("Loading ") + filename.GetFullName() + _(" Failed"));
        goto merge;
    }
    catch (std::vector<LC3AssembleException> e)
    {
        std::stringstream oss;
        for (unsigned int i = 0; i < e.size(); i++)
            oss << e[i].what() << std::endl;
        wxMessageBox(wxString::Format("BAD STUDENT! %s", oss.str()), _("Loading ") + filename.GetFullName() + _(" Failed"));
        goto merge;
    }

    //if (DoAssemble(filename)) return;
    currentFile = filename;
    SetTitle(wxString::Format("Complx - %s", filename.GetFullPath()));
    merge:

    std::map<std::string, unsigned short>::const_iterator i;
    std::map<unsigned short, std::string>::const_iterator j;
    for (i = symbol_table.begin(); i != symbol_table.end(); ++i)
    {
        state.symbols[i->first] = i->second;
    }
    for (j = rev_symbol_table.begin(); j != rev_symbol_table.end(); ++j)
    {
        state.rev_symbols[j->first] = j->second;
    }

    //DoLoad(filename);
    UpdateStatus();
    UpdateRegisters();
    UpdateMemory();

}
Ejemplo n.º 6
0
void SymbolTree::BuildTree(const wxFileName &fileName, TagEntryPtrVector_t* tags /*NULL*/)
{
    TagEntryPtrVector_t newTags;
    if ( !tags ) {
        
        // Get the current database
        ITagsStoragePtr db = TagsManagerST::Get()->GetDatabase();
        if ( ! db ) {
            Clear();
            return;
        }
        // Load the new tags from the database
        db->SelectTagsByFile(fileName.GetFullPath(), newTags);
        // Compare the new tags with the old ones
        if ( TagsManagerST::Get()->AreTheSame(newTags, m_currentTags) )
            return;
            
        m_currentTags.clear();
        m_currentTags.insert(m_currentTags.end(), newTags.begin(), newTags.end());
        
    } else {
        
        m_currentTags.clear();
        m_currentTags.insert(m_currentTags.end(), tags->begin(), tags->end());
        
    }
    
    wxWindowUpdateLocker locker(this);
    Clear();
    m_fileName = fileName;
    
    // Convert them into tree
    m_tree = TagsManagerST::Get()->Load(m_fileName, &m_currentTags);
    if ( !m_tree ) {
        return;
    }

    // Add invisible root node
    wxTreeItemId root;
    root = AddRoot(fileName.GetFullName(), 15, 15);

    TreeWalker<wxString, TagEntry> walker(m_tree->GetRoot());

    // add three items here:
    // the globals node, the mcros and the prototype node
    m_globalsNode    = AppendItem(root, wxT("Global Functions and Variables"), 2, 2, new MyTreeItemData(wxT("Global Functions and Variables"), wxEmptyString));
    m_prototypesNode = AppendItem(root, wxT("Functions Prototypes"), 2, 2, new MyTreeItemData(wxT("Functions Prototypes"), wxEmptyString));
    m_macrosNode     = AppendItem(root, wxT("Macros"), 2, 2, new MyTreeItemData(wxT("Macros"), wxEmptyString));

    // Iterate over the tree and add items
    m_sortItems.clear();

    Freeze();
    for (; !walker.End(); walker++) {
        // Add the item to the tree
        TagNode* node = walker.GetNode();

        // Skip root node
        if (node->IsRoot())
            continue;

        // Add the node
        AddItem(node);
    }
    
    SortTree(m_sortItems);
    if ( ItemHasChildren(m_globalsNode) == false ) {
        Delete(m_globalsNode);
    }
    if ( ItemHasChildren(m_prototypesNode) == false ) {
        Delete(m_prototypesNode);
    }
    if ( ItemHasChildren(m_macrosNode) == false ) {
        Delete(m_macrosNode);
    }
    Thaw();

    //select the root node by default
    if (!(GetWindowStyleFlag() & wxTR_HIDE_ROOT)) {
        //root is visible, select it
        SelectItem(GetRootItem());
    }
}
Ejemplo n.º 7
0
wxArrayString FSOExecutable::GetBinariesFromRootFolder(const wxFileName& path, const wxString& globPattern, bool quiet) {
	wxArrayString files;

	// Check args because this function gets crap tossed at it to validate
	wxString pathStr(path.GetPath());
	if (pathStr.IsEmpty())
	{
		wxLogInfo(wxT("GetBinaries called with empty root folder"));
		return files;
	}

	wxDir folder(pathStr);
	if (!folder.IsOpened())
	{
		wxLogInfo(wxT("GetBinaries called on '%s' which cannot be opened"),
			pathStr.c_str());
		return files;
	}
	wxString filename;

#if IS_APPLE // Binaries are directories on OSX.
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_DIRS);
#else
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_FILES);
#endif

	while (cont) {
#if IS_LINUX
		if ( !IsFileToIgnore(filename) ) {
#endif
		files.Add(filename);
#if IS_LINUX
		}
#endif
		cont = folder.GetNext(&filename);
	}

	// filter out launcher binaries (at least on OSX)
	for (int i = files.GetCount() - 1; i >= 0; --i) {
		if (files[i].Lower().Find(_T("launcher")) != wxNOT_FOUND) {
			files.RemoveAt(i);
		}
	}
	
#if IS_APPLE
	// find actual (Unix) executable inside .app bundle and call the path to it the "executable"
	for (wxArrayString::iterator it = files.begin(), end = files.end(); it != end; ++it) {
		wxString pathToBin = 
			wxDir::FindFirst(path.GetPath(wxPATH_GET_SEPARATOR) + *it + _T("/Contents/MacOS"),
							 _T("*"),
							 wxDIR_FILES);
		pathToBin.Replace(path.GetPath(wxPATH_GET_SEPARATOR), _T(""));
		*it = pathToBin;
	}
#endif
	
	if (!quiet) {
		wxString execType = globPattern.Lower().Find(_T("fred")) == wxNOT_FOUND ? _T("FS2") : _T("FRED2");
		wxLogInfo(_T(" Found %d %s Open executables in '%s'"),
			files.GetCount(), execType.c_str(), path.GetPath().c_str());
		
		for (size_t i = 0, n = files.GetCount(); i < n; ++i) {
			wxLogDebug(_T("Found executable: %s"), files.Item(i).c_str());
		}
	}

	return files;
}
Ejemplo n.º 8
0
// file is a misnomer as it's the name of the base help directory
bool wxExtHelpController::LoadFile(const wxString& file)
{
    wxFileName helpDir(wxFileName::DirName(file));
    helpDir.MakeAbsolute();

    bool dirExists = false;

#if wxUSE_INTL
    // If a locale is set, look in file/localename, i.e. If passed
    // "/usr/local/myapp/help" and the current wxLocale is set to be "de", then
    // look in "/usr/local/myapp/help/de/" first and fall back to
    // "/usr/local/myapp/help" if that doesn't exist.
    const wxLocale * const loc = wxGetLocale();
    if ( loc )
    {
        wxString locName = loc->GetName();

        // the locale is in general of the form xx_YY.zzzz, try the full firm
        // first and then also more general ones
        wxFileName helpDirLoc(helpDir);
        helpDirLoc.AppendDir(locName);
        dirExists = helpDirLoc.DirExists();

        if ( ! dirExists )
        {
            // try without encoding
            const wxString locNameWithoutEncoding = locName.BeforeLast(_T('.'));
            if ( !locNameWithoutEncoding.empty() )
            {
                helpDirLoc = helpDir;
                helpDirLoc.AppendDir(locNameWithoutEncoding);
                dirExists = helpDirLoc.DirExists();
            }
        }

        if ( !dirExists )
        {
            // try without country part
            wxString locNameWithoutCountry = locName.BeforeLast(_T('_'));
            if ( !locNameWithoutCountry.empty() )
            {
                helpDirLoc = helpDir;
                helpDirLoc.AppendDir(locNameWithoutCountry);
                dirExists = helpDirLoc.DirExists();
            }
        }

        if ( dirExists )
            helpDir = helpDirLoc;
    }
#endif // wxUSE_INTL

    if ( ! dirExists && !helpDir.DirExists() )
    {
        wxLogError(_("Help directory \"%s\" not found."),
                   helpDir.GetFullPath().c_str());
        return false;
    }

    const wxFileName mapFile(helpDir.GetFullPath(), WXEXTHELP_MAPFILE);
    if ( ! mapFile.FileExists() )
    {
        wxLogError(_("Help file \"%s\" not found."),
                   mapFile.GetFullPath().c_str());
        return false;
    }

    DeleteList();
    m_MapList = new wxList;
    m_NumOfEntries = 0;

    wxTextFile input;
    if ( !input.Open(mapFile.GetFullPath()) )
        return false;

    for ( wxString& line = input.GetFirstLine();
          !input.Eof();
          line = input.GetNextLine() )
    {
        if ( !ParseMapFileLine(line) )
        {
            wxLogWarning(_("Line %lu of map file \"%s\" has invalid syntax, skipped."),
                         (unsigned long)input.GetCurrentLine(),
                         mapFile.GetFullPath().c_str());
        }
    }

    if ( !m_NumOfEntries )
    {
        wxLogError(_("No valid mappings found in the file \"%s\"."),
                   mapFile.GetFullPath().c_str());
        return false;
    }

    m_helpDir = helpDir.GetFullPath(); // now it's valid
    return true;
}
Ejemplo n.º 9
0
 wxString    GetName() const { return m_file_name.GetDirs().Last(); }
Ejemplo n.º 10
0
bool BinaryDataGenerator::IsFilenameSupported(const wxFileName &fileName)
{
	return fileName.GetExt() == "bin";
}
Ejemplo n.º 11
0
bool CodeFormatter::DoClangFormat(const wxFileName& filename,
                                  wxString& formattedOutput,
                                  int& cursorPosition,
                                  int startOffset,
                                  int length,
                                  const FormatOptions& options)
{
    // clang-format
    // Build the command line to run

    if(options.GetClangFormatExe().IsEmpty()) {
        return false;
    }

    wxString command, file;
    
    clClangFormatLocator locator;
    double version = locator.GetVersion(options.GetClangFormatExe());
    
    command << options.GetClangFormatExe();
    file = filename.GetFullPath();
    ::WrapWithQuotes(command);
    ::WrapWithQuotes(file);

    command << options.ClangFormatOptionsAsString(filename, version);
    if(cursorPosition != wxNOT_FOUND) {
        command << " -cursor=" << cursorPosition;
    }

    if(startOffset != wxNOT_FOUND && length != wxNOT_FOUND) {
        command << " -offset=" << startOffset << " -length=" << length;
    }
    command << " " << file;

    // Wrap the command in the local shell
    ::WrapInShell(command);

    // Log the command
    CL_DEBUG("CodeForamtter: running:\n%s\n", command);

    // Execute clang-format and reand the output
    formattedOutput.Clear();
    IProcess::Ptr_t clangFormatProc(
        ::CreateSyncProcess(command, IProcessCreateDefault | IProcessCreateWithHiddenConsole));
    CHECK_PTR_RET_FALSE(clangFormatProc);
    clangFormatProc->WaitForTerminate(formattedOutput);
    CL_DEBUG("clang-format returned with:\n%s\n", formattedOutput);

    if(formattedOutput.IsEmpty()) {
        // crash?
        return false;
    }

    // The first line contains the cursor position
    if(cursorPosition != wxNOT_FOUND) {
        wxString metadata = formattedOutput.BeforeFirst('\n');
        JSONRoot root(metadata);
        cursorPosition = root.toElement().namedObject("cursor").toInt(wxNOT_FOUND);
        formattedOutput = formattedOutput.AfterFirst('\n');
    }
    return true;
}
 bool operator()(const wxFileName& one, const wxFileName& two) const {
     return one.GetModificationTime().GetTicks() > two.GetModificationTime().GetTicks();
 }
Ejemplo n.º 13
0
/** @brief Processes a single line from a LOF text file, doing whatever is
 * indicated on the line.
 *
 * This function should just return for lines it cannot deal with, and the
 * caller will continue to the next line of the input file
 */
void LOFImportFileHandle::lofOpenFiles(wxString* ln)
{
   wxStringTokenizer tok(*ln, wxT(" "));
   wxStringTokenizer temptok1(*ln, wxT("\""));
   wxStringTokenizer temptok2(*ln, wxT(" "));
   int tokenplace = 0;

   wxString targetfile;
   wxString tokenholder = tok.GetNextToken();

   if (tokenholder.IsSameAs(wxT("window"), false))
   {
      // set any duration/offset factors for last window, as all files were called
      doDuration();
      doScrollOffset();

      if (windowCalledOnce)
      {
         mProject = CreateNewAudacityProject();
      }

      windowCalledOnce = true;

      while (tok.HasMoreTokens())
      {
         tokenholder = tok.GetNextToken();

         if (tokenholder.IsSameAs(wxT("offset"), false))
         {
            if (tok.HasMoreTokens())
               tokenholder = tok.GetNextToken();

            if (Internat::CompatibleToDouble(tokenholder, &scrollOffset))
            {
               callScrollOffset = true;
            }
            else
            {
               /* i18n-hint: You do not need to translate "LOF" */
               wxMessageBox(_("Invalid window offset in LOF file."),
                            /* i18n-hint: You do not need to translate "LOF" */
                            _("LOF Error"), wxOK | wxCENTRE);
            }

            if (tok.HasMoreTokens())
               tokenholder = tok.GetNextToken();
         }

         if (tokenholder.IsSameAs(wxT("duration"), false))
         {
            if (tok.HasMoreTokens())
               tokenholder = tok.GetNextToken();

            if (Internat::CompatibleToDouble(tokenholder, &durationFactor))
            {
               callDurationFactor = true;
            }
            else
            {
               /* i18n-hint: You do not need to translate "LOF" */
               wxMessageBox(_("Invalid duration in LOF file."),
                            /* i18n-hint: You do not need to translate "LOF" */
                            _("LOF Error"), wxOK | wxCENTRE);
            }
         }     // End if statement

         if (tokenholder.IsSameAs(wxT("#")))
         {
            // # indicates comments; ignore line
            tok = wxStringTokenizer(wxT(""), wxT(" "));
         }
      }     // End while loop
   }        // End if statement handling "window" lines

   else if (tokenholder.IsSameAs(wxT("file"), false))
   {

      // To identify filename and open it
      tokenholder = temptok1.GetNextToken();
      targetfile = temptok1.GetNextToken();

      // If path is relative, make absolute path from LOF path
      if(!wxIsAbsolutePath(targetfile)) {
         wxFileName fName(targetfile);
         fName.Normalize(wxPATH_NORM_ALL, mLOFFileName.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
         if(fName.FileExists()) {
            targetfile = fName.GetFullPath();
         }
      }

#ifdef USE_MIDI
      // If file is a midi
      if (targetfile.AfterLast(wxT('.')).IsSameAs(wxT("mid"), false)
          ||  targetfile.AfterLast(wxT('.')).IsSameAs(wxT("midi"), false))
      {
         mProject->DoImportMIDI(targetfile);
      }

      // If not a midi, open audio file
      else

#else // !USE_MIDI
         /* if we don't have midi support, go straight on to opening as an
          * audio file. TODO: Some sort of message here? */

#endif // USE_MIDI
      {
         mProject->OpenFile(targetfile);
      }

      // Set tok to right after filename
      temptok2.SetString(targetfile);
      tokenplace = temptok2.CountTokens();

      for (int i = 0; i < tokenplace; i++)
         tokenholder = tok.GetNextToken();

      if (tok.HasMoreTokens())
      {
         tokenholder = tok.GetNextToken();

         if (tokenholder.IsSameAs(wxT("#")))
         {
            // # indicates comments; ignore line
            tok = wxStringTokenizer(wxT(""), wxT(" "));
         }

         if (tokenholder.IsSameAs(wxT("offset"), false))
         {
            if (tok.HasMoreTokens())
               tokenholder = tok.GetNextToken();
            double offset;

            // handle an "offset" specifier
            if (Internat::CompatibleToDouble(tokenholder, &offset))
            {
               Track *t;
               TrackListIterator iter(mProject->GetTracks());

               t = iter.First();

               for (int i = 1; i < CountNumTracks(mProject) - 1; i++)
                  t = iter.Next();

               // t is now the last track in the project, unless the import of
               // all tracks failed, in which case it will be null. In that
               // case we return because we cannot offset a non-existent track.
               if (t == NULL) return;
#ifdef USE_MIDI
               if (targetfile.AfterLast(wxT('.')).IsSameAs(wxT("mid"), false) ||
                   targetfile.AfterLast(wxT('.')).IsSameAs(wxT("midi"), false))
               {
                  wxMessageBox(_("MIDI tracks cannot be offset individually, only audio files can be."),
                               _("LOF Error"), wxOK | wxCENTRE);
               }
               else
#endif
               {
                  if (CountNumTracks(mProject) == 1)
                     t->SetOffset(offset);
                  else
                  {
                     if (t->GetLinked())
                        t->SetOffset(offset);

                     t = iter.Next();
                     t->SetOffset(offset);
                  }
               }
            } // end of converting "offset" argument
            else
            {
               /* i18n-hint: You do not need to translate "LOF" */
               wxMessageBox(_("Invalid track offset in LOF file."),
                            _("LOF Error"), wxOK | wxCENTRE);
            }
         }     // End if statement for "offset" parameters
      }     // End if statement (more tokens after file name)
   }     // End if statement "file" lines

   else if (tokenholder.IsSameAs(wxT("#")))
   {
      // # indicates comments; ignore line
      tok = wxStringTokenizer(wxT(""), wxT(" "));
   }
   else
   {
      // Couldn't parse a line
   }
}
Ejemplo n.º 14
0
bool wxFsEventsFileSystemWatcher::AddTree(const wxFileName& path, int events,
    const wxString& filespec)
{
    if (!path.DirExists())
    {
        return false;
    }
    wxString canonical = GetCanonicalPath(path);
    if ( canonical.empty() )
    {
        return false;
    }
    CFRunLoopRef cfLoop = CFRunLoopGetCurrent();
    wxASSERT_MSG(
        cfLoop,
        "there must be a current event loop; this file watcher needs it."
    );
    if ( ! cfLoop )
    {
        return false;
    }

    if ( m_streams.find(canonical) != m_streams.end() )
    {
        // How to take into account filespec
        // if client adds a watch for /home/*.cpp
        // and then on another call wants to add a
        // call to /home/*.h
        // Ideally we should not create another watch
        // however we would need to keep both filespecs
        // around, which we don't do now.
        return false;
    }

    // Will need to pass the desired event flags
    // and filespec to our callback via the context
    // we make sure to give the context a cleanup
    // callback.
    FSEventStreamContext ctx;
    wxFSEventWatcherContext* watcherContext = new wxFSEventWatcherContext(
        this, events, filespec.Clone()
    );
    ctx.version = 0;
    ctx.info = watcherContext;
    ctx.retain = NULL;
    ctx.release = &wxDeleteContext;
    ctx.copyDescription = NULL;
    CFTimeInterval latency = 0.2;

    wxMacUniCharBuffer pathChars(path.GetPath());
    CFStringRef pathRef = CFStringCreateWithCharacters(
        kCFAllocatorDefault,
        pathChars.GetBuffer(),
        pathChars.GetChars()
    );
    CFArrayRef pathRefs = CFArrayCreate(
        kCFAllocatorDefault, (const void**)&pathRef, 1, NULL
    );
    FSEventStreamCreateFlags flags = kFSEventStreamCreateFlagWatchRoot
        | kFSEventStreamCreateFlagFileEvents;

    FSEventStreamRef stream = FSEventStreamCreate(
        kCFAllocatorDefault,
        &wxFSEventCallback,
        &ctx,
        pathRefs, kFSEventStreamEventIdSinceNow,
        latency, flags);
    bool started = false;
    if ( stream )
    {
        FSEventStreamScheduleWithRunLoop(stream, cfLoop, kCFRunLoopDefaultMode);
        started = FSEventStreamStart(stream);
        if ( started )
        {
            m_streams[canonical] = stream;
        }
    }

    // cleanup the paths, as we own the pointers
    CFRelease(pathRef);
    CFRelease(pathRefs);

    wxASSERT_MSG(stream, "could not create FS stream");
    return started;
}
Ejemplo n.º 15
0
void CMakePlugin::OnExportMakefile(clBuildEvent& event)
{
    const wxString project = event.GetProjectName();
    const wxString config = event.GetConfigurationName();

    // Get settings
    const CMakeProjectSettings* settings = GetSettingsManager()->GetProjectSettings(project, config);

    // Doesn't exists or not enabled
    if(!settings || !settings->enabled) {
        // Unable to export makefile
        event.Skip();
        return;
    }

    // Get project directory - this is directory where the makefile is stored
    const wxFileName projectDir = GetProjectDirectory(project);

    // Targets forward inspired by
    // https://gist.github.com/doitian/4978329

    // Content of the generated makefile
    wxString content = wxString() << "# Generated by CMakePlugin\n"
                                     ".PHONY: all clean $(MAKECMDGOALS)\n"
                                     "\n";

    // Parent project is set
    if(!settings->parentProject.IsEmpty()) {
        // Configure parent project instead
        const wxString& parentProject = settings->parentProject;
        settings = GetSettingsManager()->GetProjectSettings(parentProject, config);

        // Parent project not found
        if(!settings || !settings->enabled) {
            CL_ERROR("Unable to find or not enabled parent project "
                     "'" +
                     parentProject + "' for project '" + project + "'");
            return;
        }

        // Get parent project directory
        wxFileName parentProjectDir = GetProjectDirectory(parentProject);
        parentProjectDir.MakeRelativeTo(projectDir.GetFullPath());

        // Path is relative so UNIX path system can be used
        const wxString parentProjectDirEsc = parentProjectDir.GetPath(wxPATH_NO_SEPARATOR, wxPATH_UNIX);

        // Redirect make to the parent project
        content << "# Parent project\n"
                   "PARENT          := " << parentProjectDirEsc << "\n"
                                                                   "PARENT_MAKEFILE := " << parentProject
                << ".mk\n"
                   "\n"
                   "all:\n"
                   "\t$(MAKE) -C \"$(PARENT)\" -f \"$(PARENT_MAKEFILE)\" " << project
                << "\n"
                   "\n"
                   "clean:\n"
                   "\t$(MAKE) -C \"$(PARENT)\" -f \"$(PARENT_MAKEFILE)\" " << project << " clean\n"
                                                                                         "\n";

    } else {

        // Macro expander
        // FIXME use IMacroManager (unable to find it yet)
        MacroManager* macro = MacroManager::Instance();
        wxASSERT(macro);

        // Get variables
        // Expand variables for final project
        const wxString cmake = GetConfiguration()->GetProgramPath();
        wxFileName sourceDir =
            wxFileName::DirName(macro->Expand(settings->sourceDirectory, GetManager(), project, config));
        wxFileName buildDir =
            wxFileName::DirName(macro->Expand(settings->buildDirectory, GetManager(), project, config));

        // Source dir must be relative to build directory (here is cmake called)
        sourceDir.MakeRelativeTo(buildDir.GetFullPath());
        // Build dir must be relative to project directory
        buildDir.MakeRelativeTo(projectDir.GetFullPath());

        // Relative paths
        const wxString sourceDirEsc = sourceDir.GetPath(wxPATH_NO_SEPARATOR, wxPATH_UNIX);
        const wxString buildDirEsc = buildDir.GetPath(wxPATH_NO_SEPARATOR, wxPATH_UNIX);

        // Generated makefile
        content << "CMAKE      := \"" << cmake << "\"\n"
                                                  "BUILD_DIR  := " << buildDirEsc << "\n"
                                                                                     "SOURCE_DIR := " << sourceDirEsc
                << "\n"
                   "CMAKE_ARGS := " << CreateArguments(*settings, *m_configuration)
                << "\n"
                   "\n"
                   "# Building project(s)\n"
                   "$(or $(lastword $(MAKECMDGOALS)), all): $(BUILD_DIR)/Makefile\n"
                   "\t$(MAKE) -C \"$(BUILD_DIR)\" $(MAKECMDGOALS)\n"
                   "\n"
                   "# Building directory\n"
                   "$(BUILD_DIR):\n"
                   "\t$(CMAKE) -E make_directory \"$(BUILD_DIR)\"\n"
                   "\n"
                   "# Rule that detects if cmake is called\n"
                   "$(BUILD_DIR)/Makefile: .cmake_dirty | $(BUILD_DIR)\n"
                   "\tcd \"$(BUILD_DIR)\" && $(CMAKE) $(CMAKE_ARGS) \"$(SOURCE_DIR)\"\n"
                   "\n"
                   "# This rule / file allows force cmake run\n"
                   ".cmake_dirty:\n"
                   "\t@echo '' > .cmake_dirty\n"
                   "\n";
    }

    // Path to makefile - called project directory required
    wxFileName makefile = projectDir;
    makefile.SetName(project);
    makefile.SetExt("mk");

    // Read old content from disk
    wxString oldContent;
    bool ok = ReadFileWithConversion(makefile.GetFullPath(), oldContent);

    // Write only if there are some changes
    if(!ok || content != oldContent) {
        // Write make file content
        wxFile file(makefile.GetFullPath(), wxFile::write);

        if(!file.Write(content)) {
            CL_ERROR("Unable to write custom makefile (CMakePlugin): " + makefile.GetFullPath());
        }
    }
}
Ejemplo n.º 16
0
 void        UpdateModificationTime() { m_mod_time = m_file_name.GetModificationTime(); }
Ejemplo n.º 17
0
//~~ void RunMake(const AdeConfiguration& configuration, const wxString& target) [AstadeFrame] ~~

wxConfigBase* theConfig = wxConfigBase::Get();
wxFileName make(theConfig->Read(wxS("Tools/Make")));

wxFileName configurationPath = configuration.GetFileName();
configurationPath.MakeAbsolute();

wxFileName componentPath = configuration.GetFileName();
componentPath.MakeAbsolute();
componentPath.RemoveLastDir();
AdeComponent* component = dynamic_cast<AdeComponent*>(AdeModelElement::CreateNewElement(componentPath));
assert(component);

wxString command = make.GetFullPath() + wxS(" -C \"") +
	configurationPath.GetPath() +
	wxS("\" ") +
	wxS("\"TRACECLASSES=") + GetTraceClassList() + wxS("\" \"TARGET=") +
	component->GetLabel() +
	wxS("\" ") + target;

delete component;

assert(myMakeOutput);
myMakeOutput->SetNormalStyle();
myMakeOutput->TheEdit()->Clear();
*(myMakeOutput->TheEdit()) << wxS("make started ... \n");
myMakeOutput->SetactiveConfiguration(configurationPath);

myMakeOutput->Show();
myMakeOutput->Maximize(false); //true, maximizes the window, otherwise it restores it.
Ejemplo n.º 18
0
 wxString GetPath() const { return m_lib_path.GetPath(); }
Ejemplo n.º 19
0
AVSValue AvisynthVideoProvider::Open(wxFileName const& fname, wxString const& extension) {
	IScriptEnvironment *env = avs.GetEnv();
	char *videoFilename = env->SaveString(fname.GetShortPath().mb_str(csConvLocal));

	// Avisynth file, just import it
	if (extension == ".avs") {
		LOG_I("avisynth/video") << "Opening .avs file with Import";
		decoderName = "Avisynth/Import";
		return env->Invoke("Import", videoFilename);
	}

	// Open avi file with AviSource
	if (extension == ".avi") {
		LOG_I("avisynth/video") << "Opening .avi file with AviSource";
		try {
			const char *argnames[2] = { 0, "audio" };
			AVSValue args[2] = { videoFilename, false };
			decoderName = "Avisynth/AviSource";
			return env->Invoke("AviSource", AVSValue(args,2), argnames);
		}
		// On Failure, fallback to DSS
		catch (AvisynthError &err) {
			LOG_E("avisynth/video") << err.msg;
			LOG_I("avisynth/video") << "Failed to open .avi file with AviSource, trying DirectShowSource";
		}
	}

	// Open d2v with mpeg2dec3
	if (extension == ".d2v" && env->FunctionExists("Mpeg2Dec3_Mpeg2Source")) {
		LOG_I("avisynth/video") << "Opening .d2v file with Mpeg2Dec3_Mpeg2Source";
		AVSValue script = env->Invoke("Mpeg2Dec3_Mpeg2Source", videoFilename);
		decoderName = "Avisynth/Mpeg2Dec3_Mpeg2Source";

		//if avisynth is 2.5.7 beta 2 or newer old mpeg2decs will crash without this
		if (env->FunctionExists("SetPlanarLegacyAlignment")) {
			AVSValue args[2] = { script, true };
			script = env->Invoke("SetPlanarLegacyAlignment", AVSValue(args,2));
		}
		return script;
	}

	// If that fails, try opening it with DGDecode
	if (extension == ".d2v" && env->FunctionExists("DGDecode_Mpeg2Source")) {
		LOG_I("avisynth/video") << "Opening .d2v file with DGDecode_Mpeg2Source";
		decoderName = "DGDecode_Mpeg2Source";
		return env->Invoke("Avisynth/Mpeg2Source", videoFilename);

		//note that DGDecode will also have issues like if the version is too
		// ancient but no sane person would use that anyway
	}

	if (extension == ".d2v" && env->FunctionExists("Mpeg2Source")) {
		LOG_I("avisynth/video") << "Opening .d2v file with other Mpeg2Source";
		AVSValue script = env->Invoke("Mpeg2Source", videoFilename);
		decoderName = "Avisynth/Mpeg2Source";

		//if avisynth is 2.5.7 beta 2 or newer old mpeg2decs will crash without this
		if (env->FunctionExists("SetPlanarLegacyAlignment"))
			script = env->Invoke("SetPlanarLegacyAlignment", script);

		return script;
	}

	// Try loading DirectShowSource2
	if (!env->FunctionExists("dss2")) {
		wxFileName dss2path(StandardPaths::DecodePath("?data/avss.dll"));
		if (dss2path.FileExists()) {
			env->Invoke("LoadPlugin", env->SaveString(dss2path.GetFullPath().mb_str(csConvLocal)));
		}
	}

	// If DSS2 loaded properly, try using it
	if (env->FunctionExists("dss2")) {
		LOG_I("avisynth/video") << "Opening file with DSS2";
		decoderName = "Avisynth/DSS2";
		return env->Invoke("DSS2", videoFilename);
	}

	// Try DirectShowSource
	// Load DirectShowSource.dll from app dir if it exists
	wxFileName dsspath(StandardPaths::DecodePath("?data/DirectShowSource.dll"));
	if (dsspath.FileExists()) {
		env->Invoke("LoadPlugin",env->SaveString(dsspath.GetFullPath().mb_str(csConvLocal)));
	}

	// Then try using DSS
	if (env->FunctionExists("DirectShowSource")) {
		const char *argnames[3] = { 0, "video", "audio" };
		AVSValue args[3] = { videoFilename, true, false };
		decoderName = "Avisynth/DirectShowSource";
		warning = "Warning! The file is being opened using Avisynth's DirectShowSource, which has unreliable seeking. Frame numbers might not match the real number. PROCEED AT YOUR OWN RISK!";
		LOG_I("avisynth/video") << "Opening file with DirectShowSource";
		return env->Invoke("DirectShowSource", AVSValue(args,3), argnames);
	}

	// Failed to find a suitable function
	LOG_E("avisynth/video") << "DSS function not found";
	throw VideoNotSupported("No function suitable for opening the video found");
}
Ejemplo n.º 20
0
 bool IsWritable() const { return m_lib_path.IsOk() && m_lib_path.IsDirWritable(); }
Ejemplo n.º 21
0
bool PHPProject::HasFile(const wxFileName& filename) const
{
    return filename.GetFullPath().StartsWith(GetFilename().GetPath());
}
Ejemplo n.º 22
0
bool DirManager::EnsureSafeFilename(wxFileName fName)
{
   // Quick check: If it's not even in our alias list,
   // then the file name is A-OK.

   #if 0
   printf("file name: %s\n", fName.GetFullPath().c_str());
   printf("string list:\n");
   wxStringListNode *node = aliasList.GetFirst();
   while (node)
   {
      wxString string = node->GetData();
      printf("%s\n", string.c_str());
      node = node->GetNext();
   }
   #endif

   if (!aliasList.Member(fName.GetFullPath()))
      return true;

   // If any of the following commands fail, your guess is as
   // good as mine why.  The following error message is the
   // best we can do - we'll use it if any of the renames,
   // creates, or deletes fail.
   wxString errStr =
     _( "Error: is directory write-protected or disk full?" );

   /* i18n-hint: 'old' is part of a filename used when a file is renamed. */
   // Figure out what the new name for the existing file would be.  
   /* i18n-hint: e.g. Try to go from "mysong.wav" to "mysong-old1.wav". */
   // Keep trying until we find a filename that doesn't exist.

   wxFileName renamedFile = fName;
   int i = 0;
   do {
      i++;
      /* i18n-hint: This is the pattern for filenames that are created
         when a file needs to be backed up to a different name.  For
         example, mysong would become mysong-old1, mysong-old2, etc. */
      renamedFile.SetName(wxString::Format(_("%s-old%d"), fName.GetName().c_str(), i));
   } while (wxFileExists(FILENAME(renamedFile.GetFullPath())));

   // Test creating a file by that name to make sure it will
   // be possible to do the rename

   wxFile testFile(FILENAME(renamedFile.GetFullPath()), wxFile::write);
   if (!testFile.IsOpened()) {
      wxMessageBox(errStr);
      return false;
   }
   if (!wxRemoveFile(FILENAME(renamedFile.GetFullPath()))) {
      wxMessageBox(errStr);
      return false;
   }

   printf(_("Renamed file: %s\n"), (const char *)renamedFile.GetFullPath());

   // Go through our block files and see if any indeed point to
   // the file we're concerned about.  If so, point the block file
   // to the renamed file and when we're done, perform the rename.

   bool needToRename = false;
   wxBusyCursor busy;
   blockFileHash->BeginFind();
   wxNode *n = blockFileHash->Next();
   while(n) {
      BlockFile *b = (BlockFile *)n->GetData();
      // don't worry, we don't rely on this cast unless IsAlias is true
      AliasBlockFile *ab = (AliasBlockFile*)b;

      if (b->IsAlias() && ab->GetAliasedFile() == fName) {
         needToRename = true;
         printf(_("Changing block %s\n"), (const char *)b->GetFileName().GetFullName());
         ab->ChangeAliasedFile(renamedFile);
      }

      n = blockFileHash->Next();
   }

   if (needToRename) {
      if (!wxRenameFile(FILENAME(fName.GetFullPath()),
                        FILENAME(renamedFile.GetFullPath()))) {
         // ACK!!! The renaming was unsuccessful!!!
         // (This shouldn't happen, since we tried creating a
         // file of this name and then deleted it just a
         // second earlier.)  But we'll handle this scenario
         // just in case!!!

         // Put things back where they were
         blockFileHash->BeginFind();
         n = blockFileHash->Next();
         while(n) {
            BlockFile *b = (BlockFile *)n->GetData();
            AliasBlockFile *ab = (AliasBlockFile*)b;

            if (b->IsAlias() && ab->GetAliasedFile() == renamedFile)
               ab->ChangeAliasedFile(fName);
            n = blockFileHash->Next();
         }

         // Print error message and cancel the export
         wxMessageBox(errStr);
         return false;
      }

      aliasList.Delete(fName.GetFullPath());
      aliasList.Add(renamedFile.GetFullPath());
   }

   // Success!!!  Either we successfully renamed the file,
   // or we didn't need to!
   return true;
}
Ejemplo n.º 23
0
/// Constructs a SimpleBlockFile based on sample data and writes
/// it to disk.
///
/// @param baseFileName The filename to use, but without an extension.
///                     This constructor will add the appropriate
///                     extension (.au in this case).
/// @param sampleData   The sample data to be written to this block.
/// @param sampleLen    The number of samples to be written to this block.
/// @param format       The format of the given samples.
SimpleBlockFile::SimpleBlockFile(wxFileName baseFileName,
                                 samplePtr sampleData, sampleCount sampleLen,
                                 sampleFormat format):
   BlockFile(wxFileName(baseFileName.GetFullPath() + ".au"), sampleLen)
{
   wxASSERT( !mFileName.FileExists() );

   // Open and write the file
   wxFFile file;

   if( !file.Open((const wxChar *) mFileName.GetFullPath(), "wb") )
       // Throw an exception?
       return;

   auHeader header;

   // AU files can be either big or little endian.  Which it is is
   // determined implicitly by the byte-order of the magic 0x2e736e64
   // (.snd).  We want it to be native-endian, so we write the magic
   // to memory and then let it write that to a file in native
   // endianness
   header.magic = 0x2e736e64;

   // We store the summary data at the end of the header, so the data
   // offset is the length of the summary data plus the length of the header
   header.dataOffset = sizeof(auHeader) + mSummaryInfo.totalSummaryBytes;

   // dataSize is optional, and we opt out
   header.dataSize = 0xffffffff;

   switch(format) {
      case int16Sample:
         header.encoding = AU_SAMPLE_FORMAT_16;
         break;

      case int24Sample:
         header.encoding = AU_SAMPLE_FORMAT_24;
         break;

      case floatSample:
         header.encoding = AU_SAMPLE_FORMAT_FLOAT;
         break;
   }

   // TODO: don't fabricate
   header.sampleRate = 44100;

   // BlockFiles are always mono
   header.channels = 1;

   // Write the file
   void *summaryData = BlockFile::CalcSummary(sampleData, sampleLen, format);

   file.Write(&header, sizeof(header));
   file.Write(summaryData, mSummaryInfo.totalSummaryBytes);

   if( format == int24Sample )
   {
      // we can't write the buffer directly to disk, because 24-bit samples
      // on disk need to be packed, not padded to 32 bits like they are in
      // memory
      int *int24sampleData = (int*)sampleData;

      for( int i = 0; i < sampleLen; i++ )
#if wxBYTE_ORDER == wxBIG_ENDIAN
         file.Write((char*)&int24sampleData[i] + 1, 3);
#else
         file.Write((char*)&int24sampleData[i], 3);
#endif
   }
   else
   {
      // for all other sample formats we can write straight from the buffer
      // to disk
      file.Write(sampleData, sampleLen * SAMPLE_SIZE(format));
    }
}
Ejemplo n.º 24
0
wxString xsDirNamePropIO::ToString(const wxFileName& value)
{
	return value.GetPath();
}
Ejemplo n.º 25
0
bool PluginManager::ClosePage(const wxFileName& filename)
{
    MainBook* book = clMainFrame::Get()->GetMainBook();
    LEditor* editor = book->FindEditor(filename.GetFullPath());
    return clMainFrame::Get()->GetMainBook()->ClosePage(editor);
}
Ejemplo n.º 26
0
//~~ void OmdViewPathBrowse(wxCommandEvent& event) [AstadeDirDialog] ~~

wxConfigBase* theConfig = wxConfigBase::Get();
wxFileName theFileName(theConfig->Read(wxS("Tools/OmdViewPath")));

const wxString& dir = wxFileSelector(wxS("Set OMD viewer"), theFileName.GetPath(), theFileName.GetFullName(), wxEmptyString, wxS("*"), 0, this);
wxFileName filename(dir);

if (!dir.empty())
	omdPathTextControl->SetValue(filename.GetFullPath());

Ejemplo n.º 27
0
void EDA_BASE_FRAME::CheckForAutoSaveFile( const wxFileName& aFileName,
                                           const wxString&   aBackupFileExtension )
{
    wxCHECK_RET( aFileName.IsOk(), wxT( "Invalid file name!" ) );
    wxCHECK_RET( !aBackupFileExtension.IsEmpty(), wxT( "Invalid backup file extension!" ) );

    wxFileName autoSaveFileName = aFileName;

    // Check for auto save file.
    autoSaveFileName.SetName( AUTOSAVE_PREFIX_FILENAME + aFileName.GetName() );

    wxLogTrace( traceAutoSave,
                wxT( "Checking for auto save file " ) + autoSaveFileName.GetFullPath() );

    if( !autoSaveFileName.FileExists() )
        return;

    wxString msg = wxString::Format( _(
            "Well this is potentially embarrassing!\n"
            "It appears that the last time you were editing the file\n"
            "'%s'\n"
            "it was not saved properly.  Do you wish to restore the last saved edits you made?" ),
            GetChars( aFileName.GetFullName() )
        );

    int response = wxMessageBox( msg, Pgm().App().GetAppName(), wxYES_NO | wxICON_QUESTION, this );

    // Make a backup of the current file, delete the file, and rename the auto save file to
    // the file name.
    if( response == wxYES )
    {
        // Get the backup file name.
        wxFileName backupFileName = aFileName;
        backupFileName.SetExt( aBackupFileExtension );

        // If an old backup file exists, delete it.  If an old copy of the file exists, rename
        // it to the backup file name
        if( aFileName.FileExists() )
        {
            // Remove the old file backup file.
            if( backupFileName.FileExists() )
                wxRemoveFile( backupFileName.GetFullPath() );

            // Rename the old file to the backup file name.
            if( !wxRenameFile( aFileName.GetFullPath(), backupFileName.GetFullPath() ) )
            {
                msg.Printf( _( "Could not create backup file <%s>" ),
                            GetChars( backupFileName.GetFullPath() ) );
                wxMessageBox( msg );
            }
        }

        if( !wxRenameFile( autoSaveFileName.GetFullPath(), aFileName.GetFullPath() ) )
        {
            wxMessageBox( _( "The auto save file could not be renamed to the board file name." ),
                          Pgm().App().GetAppName(), wxOK | wxICON_EXCLAMATION, this );
        }
    }
    else
    {
        wxLogTrace( traceAutoSave,
                    wxT( "Removing auto save file " ) + autoSaveFileName.GetFullPath() );

        // Remove the auto save file when using the previous file as is.
        wxRemoveFile( autoSaveFileName.GetFullPath() );
    }
}
Ejemplo n.º 28
0
void EDA_3D_CANVAS::TakeScreenshot( wxCommandEvent& event )
{
    static wxFileName fn;                 // Remember path between saves during this session only.
    wxString          FullFileName;
    wxString          file_ext, mask;
    bool              fmt_is_jpeg = false;

    // First time path is set to the project path.
    if( !fn.IsOk() )
        fn = Parent()->Prj().GetProjectFullName();

    if( event.GetId() == ID_MENU_SCREENCOPY_JPEG )
        fmt_is_jpeg = true;

    if( event.GetId() != ID_TOOL_SCREENCOPY_TOCLIBBOARD )
    {
        file_ext     = fmt_is_jpeg ? wxT( "jpg" ) : wxT( "png" );
        mask         = wxT( "*." ) + file_ext;
        fn.SetExt( file_ext );

        FullFileName = EDA_FILE_SELECTOR( _( "3D Image File Name:" ), fn.GetPath(),
                                          fn.GetFullName(), file_ext, mask, this,
                                          wxFD_SAVE | wxFD_OVERWRITE_PROMPT, true );

        if( FullFileName.IsEmpty() )
            return;

        fn = FullFileName;

        // Be sure the screen area destroyed by the file dialog is redrawn before making
        // a screen copy.
        // Without this call, under Linux the screen refresh is made to late.
        wxYield();
    }

    struct viewport_params
    {
        GLint originx;
        GLint originy;
        GLint x;
        GLint y;
    } viewport;

    // Be sure we have the latest 3D view (remember 3D view is buffered)
    Refresh();
    wxYield();

    // Build image from the 3D buffer
    wxWindowUpdateLocker noUpdates( this );
    glGetIntegerv( GL_VIEWPORT, (GLint*) &viewport );

    unsigned char*       pixelbuffer = (unsigned char*) malloc( viewport.x * viewport.y * 3 );
    unsigned char*       alphabuffer = (unsigned char*) malloc( viewport.x * viewport.y );
    wxImage image( viewport.x, viewport.y );

    glPixelStorei( GL_PACK_ALIGNMENT, 1 );
    glReadBuffer( GL_BACK_LEFT );
    glReadPixels( viewport.originx, viewport.originy,
                  viewport.x, viewport.y,
                  GL_RGB, GL_UNSIGNED_BYTE, pixelbuffer );
    glReadPixels( viewport.originx, viewport.originy,
                  viewport.x, viewport.y,
                  GL_ALPHA, GL_UNSIGNED_BYTE, alphabuffer );

    image.SetData( pixelbuffer );
    image.SetAlpha( alphabuffer );
    image = image.Mirror( false );
    wxBitmap bitmap( image );

    if( event.GetId() == ID_TOOL_SCREENCOPY_TOCLIBBOARD )
    {
        if( wxTheClipboard->Open() )
        {
            wxBitmapDataObject* dobjBmp = new wxBitmapDataObject( bitmap );

            if( !wxTheClipboard->SetData( dobjBmp ) )
                wxMessageBox( _( "Failed to copy image to clipboard" ) );

            wxTheClipboard->Flush();    /* the data in clipboard will stay
                                         * available after the application exits */
            wxTheClipboard->Close();
        }
    }
    else
    {
        wxImage image = bitmap.ConvertToImage();

        if( !image.SaveFile( FullFileName,
                             fmt_is_jpeg ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG ) )
            wxMessageBox( _( "Can't save file" ) );

        image.Destroy();
    }
}
Ejemplo n.º 29
0
//~~ void doH() [CGenerator] ~~

target.SetExt(wxS("h"));
std::ofstream out(target.GetFullPath().utf8_str());

wxFileName PrefixName(myAdeComponent->GetFileName());
PrefixName.SetFullName(wxS("prolog.h"));
wxTextFile Gprefixtext(PrefixName.GetFullPath());
if (Gprefixtext.Exists())
	Gprefixtext.Open();
if (Gprefixtext.IsOpened() && Gprefixtext.GetLineCount() > 0)
{
	wxString str;
	for (str = Gprefixtext.GetFirstLine(); !Gprefixtext.Eof(); str = Gprefixtext.GetNextLine())
		out << str.utf8_str() << std::endl;
	if (!str.empty())
		out << str.utf8_str() << std::endl;
	out << std::endl;
}

PrintHeader(out);

wxString defname(target.GetFullName());
defname.MakeUpper();
defname.Replace(wxS("."), wxS("_"));

out << "#ifndef __"   << defname.utf8_str() << std::endl;
out << "#  define __" << defname.utf8_str() << std::endl;
out << std::endl;

PrefixName = source->GetFileName();
Ejemplo n.º 30
0
bool wxFileDialog::Create(wxWindow *parent, const wxString& message,
                           const wxString& defaultDir,
                           const wxString& defaultFileName,
                           const wxString& wildCard,
                           long style, const wxPoint& pos,
                           const wxSize& sz,
                           const wxString& name)
{
    parent = GetParentForModalDialog(parent, style);

    if (!wxFileDialogBase::Create(parent, message, defaultDir, defaultFileName,
                                  wildCard, style, pos, sz, name))
    {
        return false;
    }

    if (!PreCreation(parent, pos, wxDefaultSize) ||
        !CreateBase(parent, wxID_ANY, pos, wxDefaultSize, style,
                wxDefaultValidator, wxT("filedialog")))
    {
        wxFAIL_MSG( wxT("wxFileDialog creation failed") );
        return false;
    }

    GtkFileChooserAction gtk_action;
    GtkWindow* gtk_parent = NULL;
    if (parent)
        gtk_parent = GTK_WINDOW( gtk_widget_get_toplevel(parent->m_widget) );

    const gchar* ok_btn_stock;
    if ( style & wxFD_SAVE )
    {
        gtk_action = GTK_FILE_CHOOSER_ACTION_SAVE;
        ok_btn_stock = GTK_STOCK_SAVE;
    }
    else
    {
        gtk_action = GTK_FILE_CHOOSER_ACTION_OPEN;
        ok_btn_stock = GTK_STOCK_OPEN;
    }

    m_widget = gtk_file_chooser_dialog_new(
                   wxGTK_CONV(m_message),
                   gtk_parent,
                   gtk_action,
                   GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                   ok_btn_stock, GTK_RESPONSE_ACCEPT,
                   NULL);
    g_object_ref(m_widget);
    GtkFileChooser* file_chooser = GTK_FILE_CHOOSER(m_widget);

    m_fc.SetWidget(file_chooser);

    gtk_dialog_set_default_response(GTK_DIALOG(m_widget), GTK_RESPONSE_ACCEPT);

    if ( style & wxFD_MULTIPLE )
        gtk_file_chooser_set_select_multiple(file_chooser, true);

    // local-only property could be set to false to allow non-local files to be
    // loaded. In that case get/set_uri(s) should be used instead of
    // get/set_filename(s) everywhere and the GtkFileChooserDialog should
    // probably also be created with a backend, e.g. "gnome-vfs", "default", ...
    // (gtk_file_chooser_dialog_new_with_backend). Currently local-only is kept
    // as the default - true:
    // gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(m_widget), true);

    g_signal_connect (m_widget, "response",
        G_CALLBACK (gtk_filedialog_response_callback), this);

    g_signal_connect (m_widget, "selection-changed",
        G_CALLBACK (gtk_filedialog_selchanged_callback), this);

    // deal with extensions/filters
    SetWildcard(wildCard);

    wxString defaultFileNameWithExt = defaultFileName;
    if ( !wildCard.empty() && !defaultFileName.empty() &&
            !wxFileName(defaultFileName).HasExt() )
    {
        // append the default extension, if any, to the initial file name: GTK
        // won't do it for us by default (unlike e.g. MSW)
        const wxFileName fnWC(m_fc.GetCurrentWildCard());
        if ( fnWC.HasExt() )
        {
            // Notice that we shouldn't append the extension if it's a wildcard
            // because this is not useful: the user would need to change it to use
            // some fixed extension anyhow.
            const wxString& ext = fnWC.GetExt();
            if ( ext.find_first_of("?*") == wxString::npos )
                defaultFileNameWithExt << "." << ext;
        }
    }


    // if defaultDir is specified it should contain the directory and
    // defaultFileName should contain the default name of the file, however if
    // directory is not given, defaultFileName contains both
    wxFileName fn;
    if ( defaultDir.empty() )
        fn.Assign(defaultFileNameWithExt);
    else if ( !defaultFileNameWithExt.empty() )
        fn.Assign(defaultDir, defaultFileNameWithExt);
    else
        fn.AssignDir(defaultDir);

    // set the initial file name and/or directory
    fn.MakeAbsolute(); // GTK+ needs absolute path
    const wxString dir = fn.GetPath();
    if ( !dir.empty() )
    {
        gtk_file_chooser_set_current_folder(file_chooser, wxGTK_CONV_FN(dir));
    }

    const wxString fname = fn.GetFullName();
    if ( style & wxFD_SAVE )
    {
        if ( !fname.empty() )
        {
            gtk_file_chooser_set_current_name(file_chooser, wxGTK_CONV_FN(fname));
        }

#if GTK_CHECK_VERSION(2,7,3)
        if ((style & wxFD_OVERWRITE_PROMPT)
#ifndef __WXGTK3__
            && gtk_check_version(2,7,3) == NULL
#endif
            )
        {
            gtk_file_chooser_set_do_overwrite_confirmation(file_chooser, true);
        }
#endif
    }
    else // wxFD_OPEN
    {
        if ( !fname.empty() )
        {
            gtk_file_chooser_set_filename(file_chooser,
                                          wxGTK_CONV_FN(fn.GetFullPath()));
        }
    }

    if ( style & wxFD_PREVIEW )
    {
        GtkWidget *previewImage = gtk_image_new();

        gtk_file_chooser_set_preview_widget(file_chooser, previewImage);
        g_signal_connect(m_widget, "update-preview",
                         G_CALLBACK(gtk_filedialog_update_preview_callback),
                         previewImage);
    }

    return true;
}