Beispiel #1
0
bool CSavestateWriter::WriteSave(IMemoryStream* memoryStream)
{
  using namespace XFILE;

  if (memoryStream->CurrentFrame() == nullptr)
    return false;

  m_savestate.SetSize(memoryStream->FrameSize());

  CLog::Log(LOGDEBUG, "Saving savestate to %s", m_savestate.Path().c_str());

  bool bSuccess = false;

  CFile file;
  if (file.OpenForWrite(m_savestate.Path()))
  {
    ssize_t written = file.Write(memoryStream->CurrentFrame(), memoryStream->FrameSize());
    bSuccess = (written == static_cast<ssize_t>(memoryStream->FrameSize()));
  }

  if (!bSuccess)
    CLog::Log(LOGERROR, "Failed to write savestate to %s", m_savestate.Path().c_str());

  return bSuccess;
}
Beispiel #2
0
void CPlayListM3U::Save(const std::string& strFileName) const
{
    if (!m_vecItems.size())
        return;
    std::string strPlaylist = CUtil::MakeLegalPath(strFileName);
    CFile file;
    if (!file.OpenForWrite(strPlaylist,true))
    {
        CLog::Log(LOGERROR, "Could not save M3U playlist: [%s]", strPlaylist.c_str());
        return;
    }
    std::string strLine = StringUtils::Format("%s\n",M3U_START_MARKER);
    file.Write(strLine.c_str(),strLine.size());
    for (int i = 0; i < (int)m_vecItems.size(); ++i)
    {
        CFileItemPtr item = m_vecItems[i];
        std::string strDescription=item->GetLabel();
        g_charsetConverter.utf8ToStringCharset(strDescription);
        strLine = StringUtils::Format( "%s:%i,%s\n", M3U_INFO_MARKER, item->GetMusicInfoTag()->GetDuration() / 1000, strDescription.c_str() );
        file.Write(strLine.c_str(),strLine.size());
        std::string strFileName = ResolveURL(item);
        g_charsetConverter.utf8ToStringCharset(strFileName);
        strLine = StringUtils::Format("%s\n",strFileName.c_str());
        file.Write(strLine.c_str(),strLine.size());
    }
    file.Close();
}
Beispiel #3
0
void CPlayListWPL::Save(const CStdString& strFileName) const
{
  if (!m_vecItems.size()) return ;
  CStdString strPlaylist = CUtil::MakeLegalPath(strFileName);
  CFile file;
  if (!file.OpenForWrite(strPlaylist, true))
  {
    CLog::Log(LOGERROR, "Could not save WPL playlist: [%s]", strPlaylist.c_str());
    return ;
  }
  CStdString write;
  write.AppendFormat("<?wpl version=%c1.0%c>\n", 34, 34);
  write.AppendFormat("<smil>\n");
  write.AppendFormat("    <head>\n");
  write.AppendFormat("        <meta name=%cGenerator%c content=%cMicrosoft Windows Media Player -- 10.0.0.3646%c/>\n", 34, 34, 34, 34);
  write.AppendFormat("        <author/>\n");
  write.AppendFormat("        <title>%s</title>\n", m_strPlayListName.c_str());
  write.AppendFormat("    </head>\n");
  write.AppendFormat("    <body>\n");
  write.AppendFormat("        <seq>\n");
  for (int i = 0; i < (int)m_vecItems.size(); ++i)
  {
    CFileItemPtr item = m_vecItems[i];
    write.AppendFormat("            <media src=%c%s%c/>", 34, item->m_strPath.c_str(), 34);
  }
  write.AppendFormat("        </seq>\n");
  write.AppendFormat("    </body>\n");
  write.AppendFormat("</smil>\n");
  file.Write(write.c_str(), write.size());
  file.Close();
}
Beispiel #4
0
void CPlayListPLS::Save(const CStdString& strFileName) const
{
  if (!m_vecItems.size()) return ;
  CStdString strPlaylist = CUtil::MakeLegalPath(strFileName);
  CFile file;
  if (!file.OpenForWrite(strPlaylist, true))
  {
    CLog::Log(LOGERROR, "Could not save PLS playlist: [%s]", strPlaylist.c_str());
    return;
  }
  CStdString write;
  write.AppendFormat("%s\n", START_PLAYLIST_MARKER);
  CStdString strPlayListName=m_strPlayListName;
  g_charsetConverter.utf8ToStringCharset(strPlayListName);
  write.AppendFormat("PlaylistName=%s\n", strPlayListName.c_str() );

  for (int i = 0; i < (int)m_vecItems.size(); ++i)
  {
    CFileItemPtr item = m_vecItems[i];
    CStdString strFileName=item->GetPath();
    g_charsetConverter.utf8ToStringCharset(strFileName);
    CStdString strDescription=item->GetLabel();
    g_charsetConverter.utf8ToStringCharset(strDescription);
    write.AppendFormat("File%i=%s\n", i + 1, strFileName.c_str() );
    write.AppendFormat("Title%i=%s\n", i + 1, strDescription.c_str() );
    write.AppendFormat("Length%i=%u\n", i + 1, item->GetMusicInfoTag()->GetDuration() / 1000 );
  }

  write.AppendFormat("NumberOfEntries=%i\n", m_vecItems.size());
  write.AppendFormat("Version=2\n");
  file.Write(write.c_str(), write.size());
  file.Close();
}
Beispiel #5
0
bool CEdl::WriteMPlayerEdl()
{
  if (!HasCut())
    return false;

  CFile mplayerEdlFile;
  if (!mplayerEdlFile.OpenForWrite(MPLAYER_EDL_FILENAME, true))
  {
    CLog::Log(LOGERROR, "%s - Error opening MPlayer EDL file for writing: %s", __FUNCTION__,
              MPLAYER_EDL_FILENAME);
    return false;
  }

  CStdString strBuffer;
  for (int i = 0; i < (int)m_vecCuts.size(); i++)
  {
    /* 
     * MPlayer doesn't understand the scene marker (2) or commercial break (3) identifiers that XBMC
     * supports in EDL files.
     *
     * http://www.mplayerhq.hu/DOCS/HTML/en/edl.html
     *
     * Write out mutes (1) directly. Treat commercial breaks as cuts (everything other than MUTES = 0).
     */
    strBuffer.AppendFormat("%.3f\t%.3f\t%i\n", (float)(m_vecCuts[i].start / 1000),
                                               (float)(m_vecCuts[i].end / 1000),
                                               m_vecCuts[i].action == MUTE ? 1 : 0);
  }
  mplayerEdlFile.Write(strBuffer.c_str(), strBuffer.size());
  mplayerEdlFile.Close();

  CLog::Log(LOGDEBUG, "%s - MPlayer EDL file written to: %s", __FUNCTION__, MPLAYER_EDL_FILENAME);

  return true;
}
Beispiel #6
0
void CPlayListB4S::Save(const std::string& strFileName) const
{
  if (!m_vecItems.size()) return ;
  std::string strPlaylist = strFileName;
  strPlaylist = CUtil::MakeLegalPath(strPlaylist);
  CFile file;
  if (!file.OpenForWrite(strPlaylist, true))
  {
    CLog::Log(LOGERROR, "Could not save B4S playlist: [%s]", strPlaylist.c_str());
    return ;
  }
  std::string write;
  write += StringUtils::Format("<?xml version=%c1.0%c encoding='UTF-8' standalone=%cyes%c?>\n", 34, 34, 34, 34);
  write += StringUtils::Format("<WinampXML>\n");
  write += StringUtils::Format("  <playlist num_entries=%c%i%c label=%c%s%c>\n", 34, m_vecItems.size(), 34, 34, m_strPlayListName.c_str(), 34);
  for (int i = 0; i < (int)m_vecItems.size(); ++i)
  {
    const CFileItemPtr item = m_vecItems[i];
    write += StringUtils::Format("    <entry Playstring=%cfile:%s%c>\n", 34, item->GetPath().c_str(), 34 );
    write += StringUtils::Format("      <Name>%s</Name>\n", item->GetLabel().c_str());
    write += StringUtils::Format("      <Length>%u</Length>\n", item->GetMusicInfoTag()->GetDuration());
  }
  write += StringUtils::Format("  </playlist>\n");
  write += StringUtils::Format("</WinampXML>\n");
  file.Write(write.c_str(), write.size());
  file.Close();
}
Beispiel #7
0
bool CDDSImage::WriteFile(const std::string &outputFile) const
{
  // open the file
  CFile file;
  if (!file.OpenForWrite(outputFile, true))
    return false;

  // write the header
  return file.Write("DDS ", 4) == 4 &&
    file.Write(&m_desc, sizeof(m_desc)) == sizeof(m_desc) &&
  // now the data
    file.Write(m_data, m_desc.linearSize) == (ssize_t)m_desc.linearSize;
}
Beispiel #8
0
void* CAddonCallbacksAddon::OpenFileForWrite(const void* addonData, const char* strFileName, bool bOverwrite)
{
  CAddonInterfaces* helper = (CAddonInterfaces*) addonData;
  if (!helper)
    return NULL;

  CFile* file = new CFile;
  if (file->OpenForWrite(strFileName, bOverwrite))
    return ((void*)file);

  delete file;
  return NULL;
}
Beispiel #9
0
bool CDDSImage::WriteFile(const std::string &outputFile) const
{
  // open the file
  CFile file;
  if (!file.OpenForWrite(outputFile, true))
    return false;

  // write the header
  file.Write("DDS ", 4);
  file.Write(&m_desc, sizeof(m_desc));
  // now the data
  file.Write(m_data, m_desc.linearSize);
  file.Close();
  return true;
}
Beispiel #10
0
void* Interface_Filesystem::open_file_for_write(void* kodiBase, const char* filename, bool overwrite)
{
  CAddonDll* addon = static_cast<CAddonDll*>(kodiBase);
  if (addon == nullptr || filename == nullptr)
  {
    CLog::Log(LOGERROR, "Interface_Filesystem::%s - invalid data (addon='%p', filename='%p')", __FUNCTION__, kodiBase, filename);
    return nullptr;
  }

  CFile* file = new CFile;
  if (file->OpenForWrite(filename, overwrite))
    return static_cast<void*>(file);

  delete file;
  return nullptr;
}
Beispiel #11
0
void CPlayListXML::Save(const CStdString& strFileName) const
{
  if (!m_vecItems.size()) return ;
  CStdString strPlaylist = CUtil::MakeLegalPath(strFileName);
  CFile file;
  if (!file.OpenForWrite(strPlaylist, true))
  {
    CLog::Log(LOGERROR, "Could not save WPL playlist: [%s]", strPlaylist.c_str());
    return ;
  }
  CStdString write;
  write.AppendFormat("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
  write.AppendFormat("<streams>\n");
  for (int i = 0; i < (int)m_vecItems.size(); ++i)
  {
    CFileItemPtr item = m_vecItems[i];
    write.AppendFormat("  <stream>\n" );
    write.AppendFormat("    <url>%s</url>", item->GetPath().c_str() );
    write.AppendFormat("    <name>%s</name>", item->GetLabel().c_str() );

    if ( !item->GetProperty("language").empty() )
      write.AppendFormat("    <lang>%s</lang>", item->GetProperty("language").c_str() );

    if ( !item->GetProperty("category").empty() )
      write.AppendFormat("    <category>%s</category>", item->GetProperty("category").c_str() );

    if ( !item->GetProperty("remotechannel").empty() )
      write.AppendFormat("    <channel>%s</channel>", item->GetProperty("remotechannel").c_str() );

    if ( item->m_iHasLock > 0 )
      write.AppendFormat("    <lockpassword>%s<lockpassword>", item->m_strLockCode.c_str() );

    write.AppendFormat("  </stream>\n\n" );
  }

  write.AppendFormat("</streams>\n");
  file.Write(write.c_str(), write.size());
  file.Close();
}
Beispiel #12
0
void CPlayListM3U::Save(const std::string& strFileName) const
{
  if (!m_vecItems.size())
    return;
  std::string strPlaylist = CUtil::MakeLegalPath(strFileName);
  CFile file;
  if (!file.OpenForWrite(strPlaylist,true))
  {
    CLog::Log(LOGERROR, "Could not save M3U playlist: [%s]", strPlaylist.c_str());
    return;
  }
  std::string strLine = StringUtils::Format("%s\n",StartMarker);
  if (file.Write(strLine.c_str(), strLine.size()) != static_cast<ssize_t>(strLine.size()))
    return; // error

  for (int i = 0; i < (int)m_vecItems.size(); ++i)
  {
    CFileItemPtr item = m_vecItems[i];
    std::string strDescription=item->GetLabel();
    g_charsetConverter.utf8ToStringCharset(strDescription);
    strLine = StringUtils::Format( "%s:%i,%s\n", InfoMarker, item->GetMusicInfoTag()->GetDuration() / 1000, strDescription.c_str() );
    if (file.Write(strLine.c_str(), strLine.size()) != static_cast<ssize_t>(strLine.size()))
      return; // error
    if (item->m_lStartOffset != 0 || item->m_lEndOffset != 0)
    {
      strLine = StringUtils::Format("%s:%i,%i\n", OffsetMarker, item->m_lStartOffset, item->m_lEndOffset);
      file.Write(strLine.c_str(),strLine.size());
    }
    std::string strFileName = ResolveURL(item);
    g_charsetConverter.utf8ToStringCharset(strFileName);
    strLine = StringUtils::Format("%s\n",strFileName.c_str());
    if (file.Write(strLine.c_str(), strLine.size()) != static_cast<ssize_t>(strLine.size()))
      return; // error
  }
  file.Close();
}
Beispiel #13
0
bool CFile::Cache(const CStdString& _strFileName, const CStdString& _strDest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;
  CAsyncFileCallback* helper = NULL;

  CStdString strFileName = _strFileName;
  if (CUtil::IsSpecial(strFileName))
  {
    strFileName = _P(_strFileName);
  }
  
  CStdString strDest = _strDest;
  if (CUtil::IsSpecial(strDest))
  {
    strDest = _P(_strDest);
  }
  
  if (file.Open(strFileName, READ_TRUNCATED))
  {
    CFile newFile;
    if (CUtil::IsHD(strDest)) // create possible missing dirs
    {
		CStdString strDirectory;
      CUtil::GetDirectory(strDest,strDirectory);
      CDirectory::CreateRecursive(strDirectory);
    }
    if (CFile::Exists(strDest))
      CFile::Delete(strDest);
    if (!newFile.OpenForWrite(strDest, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    /* larger then 1 meg, let's do rendering async */
    // Async render cannot be done in SDL builds because of the resulting ThreadMessage deadlock
    // we should call CAsyncFileCopy::Copy() instead.
#if defined(_XBOX)
    if( file.GetLength() > 1024*1024 )
      helper = new CAsyncFileCallback(pCallback, pContext);
#endif

    // 128k is optimal for xbox
    int iBufferSize = 128 * 1024;

    CAutoBuffer buffer(iBufferSize);
    int iRead, iWrite;

    UINT64 llFileSizeOrg = file.GetLength();
    UINT64 llPos = 0;
    int ipercent = 0;
    bool finishedReading = false;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (!finishedReading)
    {
      g_application.ResetScreenSaver();

      iRead = file.Read(buffer.get(), iBufferSize);
      if (iRead == 0) 
      {
        finishedReading = true;
        break;
      }      
      else if (iRead < 0)
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str());
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite);
        if(iWrite2 <=0)          
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str());
        break;
      }
      
      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();
      float averageSpeed = llPos / end;
      start = end;

      float fPercent;
      if (llFileSizeOrg > 0) 
      {
        fPercent = 100.0f * (float)llPos / (float)llFileSizeOrg;
      }
      else
      {
        fPercent = 50.0f;
      }

      if ((int)fPercent != ipercent)
      {
        if( helper )
        {
          helper->SetStatus((int)fPercent, averageSpeed);
          if(helper->IsCanceled())
            break;
        }
        else if( pCallback )
        {
          if (!pCallback->OnFileCallback(pContext, ipercent, averageSpeed)) 
            break;
        }

        ipercent = (int)fPercent;
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();
    
      delete helper;

    /* verify that we managed to completed the file */
    if (llFileSizeOrg > 0 && llPos != llFileSizeOrg)
    {
      CFile::Delete(strDest);
      return false;
    }
    return true;
  }
  return false;
}
Beispiel #14
0
bool CFile::Cache(const CStdString& strFileName, const CStdString& strDest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;
  CAsyncFileCallback* helper = NULL;

  if (file.Open(strFileName, true, READ_TRUNCATED))
  {
    if (file.GetLength() <= 0)
    {
      CLog::Log(LOGWARNING, "FILE::cache: the file %s has a length of 0 bytes", strFileName.c_str());
      file.Close();
      
      // Never save 0 byte files from the Plex Media Server.
      if (strFileName.Find(":32400") != -1)
        return false;
    }

    CFile newFile;
    if (CUtil::IsHD(strDest)) // create possible missing dirs
    {
      std::vector<CStdString> tokens;
      CStdString strDirectory;
      CUtil::GetDirectory(strDest,strDirectory);
      CUtil::RemoveSlashAtEnd(strDirectory);  // for the test below
      if (!(strDirectory.size() == 2 && strDirectory[1] == ':'))
      {
        CUtil::Tokenize(strDirectory,tokens,"\\");
        CStdString strCurrPath = tokens[0]+"\\";
        for (std::vector<CStdString>::iterator iter=tokens.begin()+1;iter!=tokens.end();++iter)
        {
          strCurrPath += *iter+"\\";
          CDirectory::Create(strCurrPath);
        }
      }
    }
    if (CFile::Exists(strDest))
      CFile::Delete(strDest);
    if (!newFile.OpenForWrite(strDest, true, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    /* larger then 1 meg, let's do rendering async */
// Async render cannot be done in Linux because of the resulting ThreadMessage deadlock
#ifndef _LINUX
    if( file.GetLength() > 1024*1024 )
      helper = new CAsyncFileCallback(pCallback, pContext);
#endif

    // 128k is optimal for xbox
    int iBufferSize = 128 * 1024;

    CAutoBuffer buffer(iBufferSize);
    int iRead, iWrite;

    UINT64 llFileSize = file.GetLength();
    UINT64 llFileSizeOrg = llFileSize;
    UINT64 llPos = 0;
    int ipercent = 0;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (llFileSize > 0)
    {
      g_application.ResetScreenSaver();
      unsigned int iBytesToRead = iBufferSize;
      
      /* make sure we don't try to read more than filesize*/
      if (iBytesToRead > llFileSize) iBytesToRead = llFileSize;

      iRead = file.Read(buffer.get(), iBytesToRead);
      if (iRead == 0) break;
      else if (iRead < 0) 
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str());
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite);
        if(iWrite2 <=0)          
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str());
        break;
      }
      
      llFileSize -= iRead;
      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();
      float averageSpeed = llPos / end;
      start = end;

      float fPercent = 100.0f * (float)llPos / (float)llFileSizeOrg;

      if ((int)fPercent != ipercent)
      {
        if( helper )
        {
          helper->SetStatus((int)fPercent, averageSpeed);
          if(helper->IsCanceled())
            break;
        }
        else if( pCallback )
        {
          if (!pCallback->OnFileCallback(pContext, ipercent, averageSpeed)) 
            break;
        }

        ipercent = (int)fPercent;
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();
    
    if(helper)
      delete helper;

    /* verify that we managed to completed the file */
    if (llPos != llFileSizeOrg)
    {      
      CFile::Delete(strDest);
      return false;
    }
    return true;
  }
  return false;
}
Beispiel #15
0
// This *looks* like a copy function, therefor the name "Cache" is misleading
bool CFile::Cache(const CStdString& strFileName, const CStdString& strDest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;

  if (strFileName.empty() || strDest.empty())
    return false;

  // special case for zips - ignore caching
  CURL url(strFileName);
  if (URIUtils::IsInZIP(strFileName) || URIUtils::IsInAPK(strFileName))
    url.SetOptions("?cache=no");
  if (file.Open(url.Get(), READ_TRUNCATED))
  {

    CFile newFile;
    if (URIUtils::IsHD(strDest)) // create possible missing dirs
    {
      vector<CStdString> tokens;
      CStdString strDirectory;
      URIUtils::GetDirectory(strDest,strDirectory);
      URIUtils::RemoveSlashAtEnd(strDirectory);  // for the test below
      if (!(strDirectory.size() == 2 && strDirectory[1] == ':'))
      {
        CURL url(strDirectory);
        CStdString pathsep;
#ifndef TARGET_POSIX
        pathsep = "\\";
#else
        pathsep = "/";
#endif
        CUtil::Tokenize(url.GetFileName(),tokens,pathsep.c_str());
        CStdString strCurrPath;
        // Handle special
        if (!url.GetProtocol().IsEmpty()) {
          pathsep = "/";
          strCurrPath += url.GetProtocol() + "://";
        } // If the directory has a / at the beginning, don't forget it
        else if (strDirectory[0] == pathsep[0])
          strCurrPath += pathsep;
        for (vector<CStdString>::iterator iter=tokens.begin();iter!=tokens.end();++iter)
        {
          strCurrPath += *iter+pathsep;
          CDirectory::Create(strCurrPath);
        }
      }
    }
    if (CFile::Exists(strDest))
      CFile::Delete(strDest);
    if (!newFile.OpenForWrite(strDest, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    int iBufferSize = 128 * 1024;

    CAutoBuffer buffer(iBufferSize);
    int iRead, iWrite;

    UINT64 llFileSize = file.GetLength();
    UINT64 llPos = 0;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (true)
    {
      g_application.ResetScreenSaver();

      iRead = file.Read(buffer.get(), iBufferSize);
      if (iRead == 0) break;
      else if (iRead < 0)
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite);
        if(iWrite2 <=0)
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();

      if (pCallback && end - start > 0.5 && end)
      {
        start = end;

        float averageSpeed = llPos / end;
        int ipercent = 0;
        if(llFileSize)
          ipercent = 100 * llPos / llFileSize;

        if(!pCallback->OnFileCallback(pContext, ipercent, averageSpeed))
        {
          CLog::Log(LOGERROR, "%s - User aborted copy", __FUNCTION__);
          llFileSize = (uint64_t)-1;
          break;
        }
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();

    /* verify that we managed to completed the file */
    if (llFileSize && llPos != llFileSize)
    {
      CFile::Delete(strDest);
      return false;
    }
    return true;
  }
  return false;
}
bool CGUIDialogFileBrowser::OnMessage(CGUIMessage& message)
{
  switch ( message.GetMessage() )
  {
  case GUI_MSG_WINDOW_DEINIT:
    {
      if (m_thumbLoader.IsLoading())
        m_thumbLoader.StopThread();
      CGUIDialog::OnMessage(message);
      ClearFileItems();
      m_addNetworkShareEnabled = false;
      return true;
    }
    break;

  case GUI_MSG_WINDOW_INIT:
    {
      m_bConfirmed = false;
      m_bFlip = false;
      bool bIsDir = false;
      // this code allows two different selection modes for directories
      // end the path with a slash to start inside the directory
      if (URIUtils::HasSlashAtEnd(m_selectedPath))
      {
        bIsDir = true;
        bool bFool;
        int iSource = CUtil::GetMatchingSource(m_selectedPath,m_shares,bFool);
        bFool = true;
        if (iSource > -1 && iSource < (int)m_shares.size())
        {
          if (URIUtils::PathEquals(m_shares[iSource].strPath, m_selectedPath))
            bFool = false;
        }

        if (bFool && !CDirectory::Exists(m_selectedPath))
          m_selectedPath.clear();
      }
      else
      {
        if (!CFile::Exists(m_selectedPath) && !CDirectory::Exists(m_selectedPath))
            m_selectedPath.clear();
      }

      // find the parent folder if we are a file browser (don't do this for folders)
      m_Directory->SetPath(m_selectedPath);
      if (!m_browsingForFolders && !bIsDir)
        m_Directory->SetPath(URIUtils::GetParentPath(m_selectedPath));
      Update(m_Directory->GetPath());
      m_viewControl.SetSelectedItem(m_selectedPath);
      return CGUIDialog::OnMessage(message);
    }
    break;

  case GUI_MSG_CLICKED:
    {
      if (m_viewControl.HasControl(message.GetSenderId()))  // list control
      {
        int iItem = m_viewControl.GetSelectedItem();
        int iAction = message.GetParam1();
        if (iItem < 0) break;
        CFileItemPtr pItem = (*m_vecItems)[iItem];
        if ((iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK) &&
           (!m_multipleSelection || pItem->m_bIsShareOrDrive || pItem->m_bIsFolder))
        {
          OnClick(iItem);
          return true;
        }
        else if ((iAction == ACTION_HIGHLIGHT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK || iAction == ACTION_SELECT_ITEM) &&
                (m_multipleSelection && !pItem->m_bIsShareOrDrive && !pItem->m_bIsFolder))
        {
          pItem->Select(!pItem->IsSelected());
          CGUIMessage msg(GUI_MSG_ITEM_SELECT, GetID(), message.GetSenderId(), iItem + 1);
          OnMessage(msg);
        }
      }
      else if (message.GetSenderId() == CONTROL_OK)
      {
        if (m_browsingForFolders == 2)
        {
          int iItem = m_viewControl.GetSelectedItem();

          std::string strPath;
          if (iItem == 0)
            strPath = m_selectedPath;
          else
            strPath = (*m_vecItems)[iItem]->GetPath();

          std::string strTest = URIUtils::AddFileToFolder(strPath, "1");
          CFile file;
          if (file.OpenForWrite(strTest,true))
          {
            file.Close();
            CFile::Delete(strTest);
            m_bConfirmed = true;
            Close();
          }
          else
            HELPERS::ShowOKDialogText(CVariant{257}, CVariant{20072});
        }
        else
        {
          if (m_multipleSelection)
          {
            for (int iItem = 0; iItem < m_vecItems->Size(); ++iItem)
            {
              CFileItemPtr pItem = (*m_vecItems)[iItem];
              if (pItem->IsSelected())
                m_markedPath.push_back(pItem->GetPath());
            }
          }
          m_bConfirmed = true;
          Close();
        }
        return true;
      }
      else if (message.GetSenderId() == CONTROL_CANCEL)
      {
        Close();
        return true;
      }
      else if (message.GetSenderId() == CONTROL_NEWFOLDER)
      {
        std::string strInput;
        if (CGUIKeyboardFactory::ShowAndGetInput(strInput, CVariant{g_localizeStrings.Get(119)}, false))
        {
          std::string strPath = URIUtils::AddFileToFolder(m_vecItems->GetPath(), strInput);
          if (CDirectory::Create(strPath))
            Update(m_vecItems->GetPath());
          else
            HELPERS::ShowOKDialogText(CVariant{20069}, CVariant{20072});
        }
      }
      else if (message.GetSenderId() == CONTROL_FLIP)
        m_bFlip = !m_bFlip;
    }
    break;
  case GUI_MSG_SETFOCUS:
    {
      if (m_viewControl.HasControl(message.GetControlId()) && m_viewControl.GetCurrentControl() != message.GetControlId())
      {
        m_viewControl.SetFocused();
        return true;
      }
    }
    break;
  case GUI_MSG_NOTIFY_ALL:
    { // Message is received only if this window is active
      if (message.GetParam1() == GUI_MSG_REMOVED_MEDIA)
      {
        if (m_Directory->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_Directory->GetPath());
          m_viewControl.SetSelectedItem(iItem);
        }
        else if (m_Directory->IsRemovable())
        { // check that we have this removable share still
          if (!m_rootDir.IsInSource(m_Directory->GetPath()))
          { // don't have this share any more
            if (IsActive()) Update("");
            else
            {
              m_history.ClearPathHistory();
              m_Directory->SetPath("");
            }
          }
        }
        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_SOURCES)
      { // State of the sources changed, so update our view
        if (m_Directory->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_Directory->GetPath());
          m_viewControl.SetSelectedItem(iItem);
        }
        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_PATH)
      {
        if (IsActive())
        {
          if((message.GetStringParam() == m_Directory->GetPath()) ||
             (m_Directory->IsMultiPath() && XFILE::CMultiPathDirectory::HasPath(m_Directory->GetPath(), message.GetStringParam())))
          {
            int iItem = m_viewControl.GetSelectedItem();
            Update(m_Directory->GetPath());
            m_viewControl.SetSelectedItem(iItem);
          }
        }
      }
    }
    break;

  }
  return CGUIDialog::OnMessage(message);
}
bool CGFFPatch::FFPatch(CStdString m_FFPatchFilePath, CStdString &strNEW_FFPatchFilePath)  // apply the patch
{
  CFile xbe;
  CStdString tmp;
  UINT location, startPos;
  BOOL results=FALSE;

  CLog::Log(LOGDEBUG, __FUNCTION__" - Opening file: %s",m_FFPatchFilePath.c_str());
  if (!xbe.Open(m_FFPatchFilePath))
  {
    CLog::Log(LOGDEBUG, __FUNCTION__" - ERROR: Opening file: %s",m_FFPatchFilePath.c_str());
    return false;
  }

  xbe.Open(m_FFPatchFilePath);
  int size = (int)xbe.GetLength();
  tmp.Format("%d", (size/1024) );

  CLog::Log(LOGDEBUG, __FUNCTION__" - File size is:%s kb",tmp.c_str());

  BYTE* pbuffer = new BYTE[size+1];
  if ( pbuffer == NULL )
  {
    CLog::Log(LOGDEBUG, __FUNCTION__" - Unable to allocate enough memory to load file!");
    xbe.Close();
    return false;
  }

  xbe.Read(&pbuffer[0],size);
  CLog::Log(LOGDEBUG, __FUNCTION__" - XBE File loaded successfully into memory");
  CLog::Log(LOGDEBUG, __FUNCTION__" - Examining file for potential patch locations...");
  startPos = 0;

  for (int i=0; i<50; i++)
  {
    patches[i][0] = 0;
    patches[i][1] = 0;
  }
  patchCount=0;

  while (1)
  {
    location = searchData(&pbuffer[0], startPos, size);
    if ( (location == 0) && (patchCount > 0) )  // looked through the whole file?
      break;

    if ( (location == 0) && (patchCount == 0) )
    {
      CLog::Log(LOGDEBUG, __FUNCTION__" - Unable to find key bytes to apply patch.");
      CLog::Log(LOGDEBUG, __FUNCTION__" - Could be a previos patched, homebrew or a non patchable xbe!");
      CLog::Log(LOGDEBUG, __FUNCTION__" - File not patched, exiting");
      return false;
    }

    patches[patchCount][0] = location;
    patches[patchCount][1] = examinePatch(&pbuffer[0],location);
    if (patches[patchCount][1] > 0)
    {
      switch (patches[patchCount][1])
      {
        case 1:
          CLog::Log(LOGDEBUG, __FUNCTION__" - Patch type 1 found.");
          break;
        case 2:
          CLog::Log(LOGDEBUG, __FUNCTION__" - Patch type 2 found.");
          break;
        case 3:
          CLog::Log(LOGDEBUG, __FUNCTION__" - Patch type 3 found.");
          break;
        case 4:
          CLog::Log(LOGDEBUG, __FUNCTION__" - Patch type 4 found.");
          break;
      }
      patchCount++;
    }
    startPos = location+4; // keep searching...
  }

  xbe.Close();
  if (patchCount > 0)
  {
    results = applyPatches(&pbuffer[0], patchCount);
    if (results)
    {
      // Create a new file with the patch!
      CFile file;
      CStdString strNewFFPFile;
      strNewFFPFile.Format("%s_ffp.xbe",m_FFPatchFilePath.Left(m_FFPatchFilePath.GetLength()-4));
      if(file.OpenForWrite(strNewFFPFile.c_str(),true,true))
      {
        file.Write(&pbuffer[0],size);
        file.Close();
        CLog::Log(LOGDEBUG, __FUNCTION__" - File written and closed.");
        strNEW_FFPatchFilePath = strNewFFPFile;
      } 
      else 
        return false;
    }
  }
  delete []pbuffer;
  return true;
}