Example #1
0
void CPVRManager::ResetDatabase(bool bShowProgress /* = true */)
{
  CLog::Log(LOGNOTICE,"PVRManager - %s - clearing the PVR database", __FUNCTION__);

  /* close the epg progress dialog, or we'll get a deadlock */
  g_PVREpg->CloseUpdateDialog();

  CGUIDialogProgress* pDlgProgress = NULL;
  if (bShowProgress)
  {
    pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
    pDlgProgress->SetLine(0, "");
    pDlgProgress->SetLine(1, g_localizeStrings.Get(19186));
    pDlgProgress->SetLine(2, "");
    pDlgProgress->StartModal();
    pDlgProgress->Progress();
  }

  if (m_addons->IsPlaying())
  {
    CLog::Log(LOGNOTICE,"PVRManager - %s - stopping playback", __FUNCTION__);
    g_application.StopPlaying();
  }

  if (bShowProgress)
  {
    pDlgProgress->SetPercentage(10);
    pDlgProgress->Progress();
  }

  /* stop the thread */
  if (g_guiSettings.GetBool("pvrmanager.enabled"))
    Stop();

  if (bShowProgress)
  {
    pDlgProgress->SetPercentage(20);
    pDlgProgress->Progress();
  }

  if (m_database->Open())
  {
    /* clean the EPG database */
    m_epg->Clear(true);
    if (bShowProgress)
    {
      pDlgProgress->SetPercentage(30);
      pDlgProgress->Progress();
    }

    m_database->DeleteChannelGroups();
    if (bShowProgress)
    {
      pDlgProgress->SetPercentage(50);
      pDlgProgress->Progress();
    }

    /* delete all channels */
    m_database->DeleteChannels();
    if (bShowProgress)
    {
      pDlgProgress->SetPercentage(70);
      pDlgProgress->Progress();
    }

    /* delete all channel settings */
    m_database->DeleteChannelSettings();
    if (bShowProgress)
    {
      pDlgProgress->SetPercentage(80);
      pDlgProgress->Progress();
    }

    /* delete all client information */
    m_database->DeleteClients();
    if (bShowProgress)
    {
      pDlgProgress->SetPercentage(90);
      pDlgProgress->Progress();
    }

    m_database->Close();
  }

  CLog::Log(LOGNOTICE,"PVRManager - %s - PVR database cleared", __FUNCTION__);

  if (g_guiSettings.GetBool("pvrmanager.enabled"))
  {
    CLog::Log(LOGNOTICE,"PVRManager - %s - restarting the PVRManager", __FUNCTION__);
    Cleanup();
    Start();
  }

  if (bShowProgress)
  {
    pDlgProgress->SetPercentage(100);
    pDlgProgress->Close();
  }
}
/*----------------------------------------------------------------------
|   CUPnPDirectory::GetDirectory
+---------------------------------------------------------------------*/
bool
CUPnPDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
    CGUIDialogProgress* dlgProgress = NULL;

    CUPnP* upnp = CUPnP::GetInstance();

    /* upnp should never be cached, it has internal cache */
    items.SetCacheToDisc(CFileItemList::CACHE_NEVER);

    // start client if it hasn't been done yet
    bool client_started = upnp->IsClientStarted();
    upnp->StartClient();

    // We accept upnp://devuuid/[item_id/]
    NPT_String path = strPath.c_str();
    if (!path.StartsWith("upnp://", true)) {
        return false;
    }

    if (path.Compare("upnp://", true) == 0) {
        // root -> get list of devices
        const NPT_Lock<PLT_DeviceMap>& devices = upnp->m_MediaBrowser->GetMediaServers();
        const NPT_List<PLT_DeviceMapEntry*>& entries = devices.GetEntries();
        NPT_List<PLT_DeviceMapEntry*>::Iterator entry = entries.GetFirstItem();
        while (entry) {
            PLT_DeviceDataReference device = (*entry)->GetValue();
            NPT_String name = device->GetFriendlyName();
            NPT_String uuid = (*entry)->GetKey();

            CFileItemPtr pItem(new CFileItem((const char*)name));
            pItem->m_strPath = (const char*) "upnp://" + uuid + "/";
            pItem->m_bIsFolder = true;
            pItem->SetThumbnailImage((const char*)device->GetIconUrl("image/jpeg"));

            items.Add(pItem);

            ++entry;
        }
    } else {
        if (!path.EndsWith("/")) path += "/";

        // look for nextslash
        int next_slash = path.Find('/', 7);

        NPT_String uuid = (next_slash==-1)?path.SubString(7):path.SubString(7, next_slash-7);
        NPT_String object_id = (next_slash==-1)?"":path.SubString(next_slash+1);
        object_id.TrimRight("/");
        if (object_id.GetLength()) {
            CStdString tmp = (char*) object_id;
            CUtil::UrlDecode(tmp);
            object_id = tmp;
        }

        // look for device in our list
        // (and wait for it to respond for 5 secs if we're just starting upnp client)
        NPT_TimeStamp watchdog;
        NPT_System::GetCurrentTimeStamp(watchdog);
        watchdog += 5.f;

        PLT_DeviceDataReference* device;
        for (;;) {
            const NPT_Lock<PLT_DeviceMap>& devices = upnp->m_MediaBrowser->GetMediaServers();
            if (NPT_SUCCEEDED(devices.Get(uuid, device)) && device)
                break;

            // fail right away if device not found and upnp client was already running
            if (client_started)
                goto failure;

            // otherwise check if we've waited long enough without success
            NPT_TimeStamp now;
            NPT_System::GetCurrentTimeStamp(now);
            if (now > watchdog)
                goto failure;

            // sleep a bit and try again
            NPT_System::Sleep(NPT_TimeInterval(1, 0));
        }

        // issue a browse request with object_id
        // if object_id is empty use "0" for root
        object_id = object_id.IsEmpty()?"0":object_id;

        // just a guess as to what types of files we want
        bool video = true;
        bool audio = true;
        bool image = true;
        m_strFileMask.TrimLeft("/");
        if (!m_strFileMask.IsEmpty()) {
            video = m_strFileMask.Find(".wmv") >= 0;
            audio = m_strFileMask.Find(".wma") >= 0;
            image = m_strFileMask.Find(".jpg") >= 0;
        }

        // special case for Windows Media Connect and WMP11 when looking for root
        // We can target which root subfolder we want based on directory mask
        if (object_id == "0" && (((*device)->GetFriendlyName().Find("Windows Media Connect", 0, true) >= 0) ||
                                 ((*device)->m_ModelName == "Windows Media Player Sharing"))) {

            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "1";
            } else if (!audio && video && !image) {
                // video
                object_id = "2";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "3";
            }
        }

#ifdef DISABLE_SPECIALCASE
        // same thing but special case for XBMC
        if (object_id == "0" && (((*device)->m_ModelName.Find("XBMC", 0, true) >= 0) ||
                                 ((*device)->m_ModelName.Find("Xbox Media Center", 0, true) >= 0))) {
            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "virtualpath://upnpmusic";
            } else if (!audio && video && !image) {
                // video
                object_id = "virtualpath://upnpvideo";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "virtualpath://upnppictures";
            }
        }
#endif
        // bring up dialog if object is not cached
        if (!upnp->m_MediaBrowser->IsCached(uuid, object_id)) {
            dlgProgress = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
            if (dlgProgress) {
                dlgProgress->ShowProgressBar(false);
                dlgProgress->SetCanCancel(false);
                dlgProgress->SetHeading(20334);
                dlgProgress->SetLine(0, 194);
                dlgProgress->SetLine(1, "");
                dlgProgress->SetLine(2, "");
                dlgProgress->StartModal();
            }
        }

        // if error, return now, the device could have gone away
        // this will make us go back to the sources list
        PLT_MediaObjectListReference list;
        NPT_Result res = upnp->m_MediaBrowser->Browse(*device, object_id, list);
        if (NPT_FAILED(res)) goto failure;

        // empty list is ok
        if (list.IsNull()) goto cleanup;

        PLT_MediaObjectList::Iterator entry = list->GetFirstItem();
        while (entry) {
            // disregard items with wrong class/type
            if( (!video && (*entry)->m_ObjectClass.type.CompareN("object.item.videoitem", 21,true) == 0)
             || (!audio && (*entry)->m_ObjectClass.type.CompareN("object.item.audioitem", 21,true) == 0)
             || (!image && (*entry)->m_ObjectClass.type.CompareN("object.item.imageitem", 21,true) == 0) )
            {
                ++entry;
                continue;
            }

            // never show empty containers in media views
            if((*entry)->IsContainer()) {
                if( (audio || video || image)
                 && ((PLT_MediaContainer*)(*entry))->m_ChildrenCount == 0) {
                    ++entry;
                    continue;
                }
            }

            CFileItemPtr pItem(new CFileItem((const char*)(*entry)->m_Title));
            pItem->SetLabelPreformated(true);
            pItem->m_bIsFolder = (*entry)->IsContainer();

            // if it's a container, format a string as upnp://uuid/object_id
            if (pItem->m_bIsFolder) {
                CStdString id = (char*) (*entry)->m_ObjectID;
                CUtil::URLEncode(id);
                pItem->m_strPath = (const char*) "upnp://" + uuid + "/" + id.c_str() + "/";
            } else {
                if ((*entry)->m_Resources.GetItemCount()) {
                    PLT_MediaItemResource& resource = (*entry)->m_Resources[0];

                    // look for a resource with "xbmc-get" protocol
                    // if we can't find one, keep the first resource
                    NPT_ContainerFind((*entry)->m_Resources,
                                      CProtocolFinder("xbmc-get"),
                                      resource);

                    CLog::Log(LOGDEBUG, "CUPnPDirectory::GetDirectory - resource protocol info '%s'", (const char*)(resource.m_ProtocolInfo));

                    // if it's an item, path is the first url to the item
                    // we hope the server made the first one reachable for us
                    // (it could be a format we dont know how to play however)
                    pItem->m_strPath = (const char*) resource.m_Uri;

                    // set metadata
                    if (resource.m_Size > 0) {
                        pItem->m_dwSize  = resource.m_Size;
                    }

                    // set a general content type
                    CStdString type = (const char*)(*entry)->m_ObjectClass.type.Left(21);
                    if     (type.Equals("object.item.videoitem"))
                        pItem->SetContentType("video/octet-stream");
                    else if(type.Equals("object.item.audioitem"))
                        pItem->SetContentType("audio/octet-stream");
                    else if(type.Equals("object.item.imageitem"))
                        pItem->SetContentType("image/octet-stream");

                    // look for content type in protocol info
                    if (resource.m_ProtocolInfo.GetLength()) {
                        char proto[1024];
                        char dummy1[1024];
                        char ct[1204];
                        char dummy2[1024];
                        int fields = sscanf(resource.m_ProtocolInfo, "%[^:]:%[^:]:%[^:]:%[^:]", proto, dummy1, ct, dummy2);
                        if (fields == 4) {
                            if (strcmp(ct, "application/octet-stream") != 0) {
                                pItem->SetContentType(ct);
                            }
                        } else {
                            CLog::Log(LOGERROR, "CUPnPDirectory::GetDirectory - invalid protocol info '%s'", (const char*)(resource.m_ProtocolInfo));
                        }
                    }

                    // look for date?
                    if((*entry)->m_Description.date.GetLength()) {
                        SYSTEMTIME time = {};
                        sscanf((*entry)->m_Description.date, "%hu-%hu-%huT%hu:%hu:%hu",
                               &time.wYear, &time.wMonth, &time.wDay, &time.wHour, &time.wMinute, &time.wSecond);
                        pItem->m_dateTime = time;
                    }

                    // look for metadata
                    if( (*entry)->m_ObjectClass.type.CompareN("object.item.videoitem", 21,true) == 0 ) {
                        pItem->SetLabelPreformated(false);
                        CUPnP::PopulateTagFromObject(*pItem->GetVideoInfoTag(), *(*entry), &resource);
                    } else if( (*entry)->m_ObjectClass.type.CompareN("object.item.audioitem", 21,true) == 0 ) {
                        pItem->SetLabelPreformated(false);
                        CUPnP::PopulateTagFromObject(*pItem->GetMusicInfoTag(), *(*entry), &resource);
                    } else if( (*entry)->m_ObjectClass.type.CompareN("object.item.imageitem", 21,true) == 0 ) {
                      //CPictureInfoTag* tag = pItem->GetPictureInfoTag();
                    }
                }
            }

            // if there is a thumbnail available set it here
            if((*entry)->m_ExtraInfo.album_art_uri.GetLength())
                pItem->SetThumbnailImage((const char*) (*entry)->m_ExtraInfo.album_art_uri);
            else if((*entry)->m_Description.icon_uri.GetLength())
                pItem->SetThumbnailImage((const char*) (*entry)->m_Description.icon_uri);

            items.Add(pItem);

            ++entry;
        }
    }

cleanup:
    if (dlgProgress) dlgProgress->Close();
    return true;

failure:
    if (dlgProgress) dlgProgress->Close();
    return false;
}
void CGUIWindowFileManager::OnPopupMenu(int list, int item, bool bContextDriven /* = true */)
{
  if (list < 0 || list >= 2) return ;
  bool bDeselect = SelectItem(list, item);
  // calculate the position for our menu
  float posX = 200;
  float posY = 100;
  const CGUIControl *pList = GetControl(CONTROL_LEFT_LIST + list);
  if (pList)
  {
    posX = pList->GetXPosition() + pList->GetWidth() / 2;
    posY = pList->GetYPosition() + pList->GetHeight() / 2;
  }

  CFileItemPtr pItem = m_vecItems[list]->Get(item);
  if (!pItem.get())
    return;

  if (m_Directory[list]->IsVirtualDirectoryRoot())
  {
    if (item < 0)
    { // TODO: We should add the option here for shares to be added if there aren't any
      return ;
    }

    // and do the popup menu
    if (CGUIDialogContextMenu::SourcesMenu("files", pItem, posX, posY))
    {
      m_rootDir.SetSources(*CMediaSourceSettings::Get().GetSources("files"));
      if (m_Directory[1 - list]->IsVirtualDirectoryRoot())
        Refresh();
      else
        Refresh(list);
      return ;
    }
    pItem->Select(false);
    return ;
  }
  // popup the context menu

  bool showEntry = false;
  if (item >= m_vecItems[list]->Size()) item = -1;
  if (item >= 0)
    showEntry=(!pItem->IsParentFolder() || (pItem->IsParentFolder() && m_vecItems[list]->GetSelectedCount()>0));

  // determine available players
  VECPLAYERCORES vecCores;
  CPlayerCoreFactory::Get().GetPlayers(*pItem, vecCores);

  // add the needed buttons
  CContextButtons choices;
  if (item >= 0)
  {
    //The ".." item is not selectable. Take that into account when figuring out if all items are selected
    int notSelectable = CSettings::Get().GetBool("filelists.showparentdiritems") ? 1 : 0;
    if (NumSelected(list) <  m_vecItems[list]->Size() - notSelectable)
      choices.Add(1, 188); // SelectAll
    if (!pItem->IsParentFolder())
      choices.Add(2,  XFILE::CFavouritesDirectory::IsFavourite(pItem.get(), GetID()) ? 14077 : 14076); // Add/Remove Favourite
    if (vecCores.size() > 1)
      choices.Add(3, 15213); // Play Using...
    if (CanRename(list) && !pItem->IsParentFolder())
      choices.Add(4, 118); // Rename
    if (CanDelete(list) && showEntry)
      choices.Add(5, 117); // Delete
    if (CanCopy(list) && showEntry)
      choices.Add(6, 115); // Copy
    if (CanMove(list) && showEntry)
      choices.Add(7, 116); // Move
  }
  if (CanNewFolder(list))
    choices.Add(8, 20309); // New Folder
  if (item >= 0 && pItem->m_bIsFolder && !pItem->IsParentFolder())
    choices.Add(9, 13393); // Calculate Size
  choices.Add(11, 20128); // Go To Root
  choices.Add(12, 523);     // switch media
  if (CJobManager::GetInstance().IsProcessing("filemanager"))
    choices.Add(13, 167);

  int btnid = CGUIDialogContextMenu::ShowAndGetChoice(choices);
  if (btnid == 1)
  {
    OnSelectAll(list);
    bDeselect=false;
  }
  if (btnid == 2)
  {
    XFILE::CFavouritesDirectory::AddOrRemove(pItem.get(), GetID());
    return;
  }
  if (btnid == 3)
  {
    VECPLAYERCORES vecCores;
    CPlayerCoreFactory::Get().GetPlayers(*pItem, vecCores);
    g_application.m_eForcedNextPlayer = CPlayerCoreFactory::Get().SelectPlayerDialog(vecCores);
    if (g_application.m_eForcedNextPlayer != EPC_NONE)
      OnStart(pItem.get());
  }
  if (btnid == 4)
    OnRename(list);
  if (btnid == 5)
    OnDelete(list);
  if (btnid == 6)
    OnCopy(list);
  if (btnid == 7)
    OnMove(list);
  if (btnid == 8)
    OnNewFolder(list);
  if (btnid == 9)
  {
    // setup the progress dialog, and show it
    CGUIDialogProgress *progress = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
    if (progress)
    {
      progress->SetHeading(CVariant{13394});
      for (int i=0; i < 3; i++)
        progress->SetLine(i, CVariant{""});
      progress->Open();
    }

    //  Calculate folder size for each selected item
    for (int i=0; i<m_vecItems[list]->Size(); ++i)
    {
      CFileItemPtr pItem2=m_vecItems[list]->Get(i);
      if (pItem2->m_bIsFolder && pItem2->IsSelected())
      {
        int64_t folderSize = CalculateFolderSize(pItem2->GetPath(), progress);
        if (folderSize >= 0)
        {
          pItem2->m_dwSize = folderSize;
          if (folderSize == 0)
            pItem2->SetLabel2(StringUtils::SizeToString(folderSize));
          else
            pItem2->SetFileSizeLabel();
        }
      }
    }
    if (progress)
      progress->Close();
  }
  if (btnid == 11)
  {
    Update(list,"");
    return;
  }
  if (btnid == 12)
  {
    CGUIDialogContextMenu::SwitchMedia("files", m_vecItems[list]->GetPath());
    return;
  }
  if (btnid == 13)
    CancelJobs();

  if (bDeselect && item >= 0 && item < m_vecItems[list]->Size())
  { // deselect item as we didn't do anything
    pItem->Select(false);
  }
}
Example #4
0
void CPVRManager::ResetDatabase(bool bResetEPGOnly /* = false */)
{
  CLog::Log(LOGNOTICE,"PVRManager - %s - clearing the PVR database", __FUNCTION__);

  g_EpgContainer.Stop();

  CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  pDlgProgress->SetLine(0, StringUtils::EmptyString);
  pDlgProgress->SetLine(1, g_localizeStrings.Get(19186)); // All data in the PVR database is being erased
  pDlgProgress->SetLine(2, StringUtils::EmptyString);
  pDlgProgress->StartModal();
  pDlgProgress->Progress();

  if (m_addons && m_addons->IsPlaying())
  {
    CLog::Log(LOGNOTICE,"PVRManager - %s - stopping playback", __FUNCTION__);
    CApplicationMessenger::Get().MediaStop();
  }

  pDlgProgress->SetPercentage(10);
  pDlgProgress->Progress();

  /* reset the EPG pointers */
  m_database->ResetEPG();

  /* stop the thread */
  Stop();

  pDlgProgress->SetPercentage(20);
  pDlgProgress->Progress();

  if (!m_database)
    m_database = new CPVRDatabase;

  if (m_database && m_database->Open())
  {
    /* clean the EPG database */
    g_EpgContainer.Reset();
    pDlgProgress->SetPercentage(30);
    pDlgProgress->Progress();

    if (!bResetEPGOnly)
    {
      m_database->DeleteChannelGroups();
      pDlgProgress->SetPercentage(50);
      pDlgProgress->Progress();

      /* delete all channels */
      m_database->DeleteChannels();
      pDlgProgress->SetPercentage(70);
      pDlgProgress->Progress();

      /* delete all channel settings */
      m_database->DeleteChannelSettings();
      pDlgProgress->SetPercentage(80);
      pDlgProgress->Progress();

      /* delete all client information */
      m_database->DeleteClients();
      pDlgProgress->SetPercentage(90);
      pDlgProgress->Progress();
    }

    m_database->Close();
  }

  CLog::Log(LOGNOTICE,"PVRManager - %s - %s database cleared", __FUNCTION__, bResetEPGOnly ? "EPG" : "PVR and EPG");

  if (g_guiSettings.GetBool("pvrmanager.enabled"))
  {
    CLog::Log(LOGNOTICE,"PVRManager - %s - restarting the PVRManager", __FUNCTION__);
    m_database->Open();
    Cleanup();
    Start();
  }

  pDlgProgress->SetPercentage(100);
  pDlgProgress->Close();
}
Example #5
0
bool CWeather::GetSearchResults(const CStdString &strSearch, CStdString &strResult)
{
  // Check to see if the user entered a weather.com code
  if (strSearch.size() == 8)
  {
    strResult = "";
    int i = 0;
    for (i = 0; i < 4; ++i)
    {
      strResult += toupper(strSearch[i]);
      if (!isalpha(strSearch[i]))
        break;
    }
    if (i == 4)
    {
      for ( ; i < 8; ++i)
      {
        strResult += strSearch[i];
        if (!isdigit(strSearch[i]))
          break;
      }
      if (i == 8)
      {
        return true; // match
      }
    }
    // no match, wipe string
    strResult = "";
  }

  CGUIDialogSelect *pDlgSelect = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
  CGUIDialogProgress *pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);

  //do the download
  CStdString strURL;
  CStdString strXML;
  XFILE::CFileCurl httpUtil;

  if (pDlgProgress)
  {
    pDlgProgress->SetHeading(410);       //"Accessing Weather.com"
    pDlgProgress->SetLine(0, 194);       //"Searching"
    pDlgProgress->SetLine(1, strSearch);
    pDlgProgress->SetLine(2, "");
    pDlgProgress->StartModal();
    pDlgProgress->Progress();
  }

  strURL.Format("http://xoap.weather.com/search/search?where=%s", strSearch);

  if (!httpUtil.Get(strURL, strXML))
  {
    if (pDlgProgress)
      pDlgProgress->Close();
    return false;
  }

  //some select dialog init stuff
  if (!pDlgSelect)
  {
    if (pDlgProgress)
      pDlgProgress->Close();
    return false;
  }

  pDlgSelect->SetHeading(396); //"Select Location"
  pDlgSelect->Reset();

  ///////////////////////////////
  // load the xml file
  ///////////////////////////////
  TiXmlDocument xmlDoc;
  xmlDoc.Parse(strXML.c_str());
  if (xmlDoc.Error())
    return false;

  TiXmlElement *pRootElement = xmlDoc.RootElement();
  if (pRootElement)
  {
    CStdString strItemTmp;
    TiXmlElement *pElement = pRootElement->FirstChildElement("loc");
    while (pElement)
    {
      if (!pElement->NoChildren())
      {
        strItemTmp.Format("%s - %s", pElement->Attribute("id"), pElement->FirstChild()->Value());
        pDlgSelect->Add(strItemTmp);
      }
      pElement = pElement->NextSiblingElement("loc");
    }
  }

  if (pDlgProgress)
    pDlgProgress->Close();

  pDlgSelect->EnableButton(true, 222); //'Cancel' button returns to weather settings
  pDlgSelect->DoModal();

  if (pDlgSelect->GetSelectedLabel() < 0)
  {
    if (pDlgSelect->IsButtonPressed())
    {
      pDlgSelect->Close(); //close the select dialog and return to weather settings
      return true;
    }
  }

  //copy the selected code into the settings
  if (pDlgSelect->GetSelectedLabel() >= 0)
    strResult = pDlgSelect->GetSelectedLabelText();

  if (pDlgProgress)
    pDlgProgress->Close();

  return true;
}
Example #6
0
void CPVRManager::ResetDatabase(bool bResetEPGOnly /* = false */)
{
  CLog::Log(LOGNOTICE,"PVRManager - %s - clearing the PVR database", __FUNCTION__);

  g_EpgContainer.Stop();

  CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  pDlgProgress->SetHeading(CVariant{313});
  pDlgProgress->SetLine(0, CVariant{g_localizeStrings.Get(19187)}); // All data in the PVR database is being erased
  pDlgProgress->SetLine(1, CVariant{""});
  pDlgProgress->SetLine(2, CVariant{""});
  pDlgProgress->Open();
  pDlgProgress->Progress();

  if (m_addons->IsPlaying())
  {
    CLog::Log(LOGNOTICE,"PVRManager - %s - stopping playback", __FUNCTION__);
    CApplicationMessenger::GetInstance().SendMsg(TMSG_MEDIA_STOP);
  }

  pDlgProgress->SetPercentage(10);
  pDlgProgress->Progress();

  /* reset the EPG pointers */
  if (m_database)
    m_database->ResetEPG();

  /* stop the thread */
  Stop();

  pDlgProgress->SetPercentage(20);
  pDlgProgress->Progress();

  if (!m_database)
    m_database = new CPVRDatabase;

  if (m_database && m_database->Open())
  {
    /* clean the EPG database */
    g_EpgContainer.Reset();
    pDlgProgress->SetPercentage(30);
    pDlgProgress->Progress();

    if (!bResetEPGOnly)
    {
      m_database->DeleteChannelGroups();
      pDlgProgress->SetPercentage(50);
      pDlgProgress->Progress();

      /* delete all channels */
      m_database->DeleteChannels();
      pDlgProgress->SetPercentage(70);
      pDlgProgress->Progress();

      /* delete all channel and recording settings */
      CVideoDatabase videoDatabase;

      if (videoDatabase.Open())
      {
        videoDatabase.EraseVideoSettings("pvr://channels/");
        videoDatabase.EraseVideoSettings(CPVRRecordingsPath::PATH_RECORDINGS);
        videoDatabase.Close();
      }

      pDlgProgress->SetPercentage(80);
      pDlgProgress->Progress();

      /* delete all client information */
      pDlgProgress->SetPercentage(90);
      pDlgProgress->Progress();
    }

    m_database->Close();
  }

  CLog::Log(LOGNOTICE,"PVRManager - %s - %s database cleared", __FUNCTION__, bResetEPGOnly ? "EPG" : "PVR and EPG");

  CLog::Log(LOGNOTICE,"PVRManager - %s - restarting the PVRManager", __FUNCTION__);
  m_database->Open();
  Cleanup();
  Start();

  pDlgProgress->SetPercentage(100);
  pDlgProgress->Close();
}
Example #7
0
void CGUIDialogMusicInfo::RefreshInfo()
{
  // Double check we have permission (button should be hidden when not)
  const CProfilesManager &profileManager = CServiceBroker::GetProfileManager();
  if (!profileManager.GetCurrentProfile().canWriteDatabases() && !g_passwordManager.bMasterUser)
    return;

  // Check if scanning
  if (g_application.IsMusicScanning())
  {
    HELPERS::ShowOKDialogText(CVariant{ 189 }, CVariant{ 14057 });
    return;
  }

  CGUIDialogProgress* dlgProgress = CServiceBroker::GetGUI()->GetWindowManager().
    GetWindow<CGUIDialogProgress>(WINDOW_DIALOG_PROGRESS);
  if (!dlgProgress)
    return;

  if (m_bArtistInfo)
  { // Show dialog box indicating we're searching for the artist
    dlgProgress->SetHeading(CVariant{ 21889 });
    dlgProgress->SetLine(0, CVariant{ m_artist.strArtist });
    dlgProgress->SetLine(1, CVariant{ "" });
    dlgProgress->SetLine(2, CVariant{ "" });
  }
  else
  { // Show dialog box indicating we're searching for the album
    dlgProgress->SetHeading(CVariant{ 185 });
    dlgProgress->SetLine(0, CVariant{ m_album.strAlbum });
    dlgProgress->SetLine(1, CVariant{ m_album.strArtistDesc });
    dlgProgress->SetLine(2, CVariant{ "" });
  }
  dlgProgress->Open();

  SetScrapedInfo(false);
  // Start separate job to scrape info and fill list of art types.
  CJobManager::GetInstance().AddJob(new CRefreshInfoJob(dlgProgress), nullptr, CJob::PRIORITY_HIGH);

  // Wait for refresh to complete or be canceled, but render every 10ms so that the
  // pointer movements works on dialog even when job is reporting progress infrequently
  if (dlgProgress)
    dlgProgress->Wait(10);

  if (dlgProgress->IsCanceled())
  {
    return;
  }

  // Show message when scraper was unsuccesfull
  if (!HasScrapedInfo())
  {
    if (m_bArtistInfo)
      HELPERS::ShowOKDialogText(CVariant{ 21889 }, CVariant{ 20199 });
    else
      HELPERS::ShowOKDialogText(CVariant{ 185 }, CVariant{ 500 });
    return;
  }

  //  Show new values on screen
  Update();
  m_hasRefreshed = true;

  if (dlgProgress)
    dlgProgress->Close();
}
void CGUIWindowBoxeeWizardNetwork::ShowWirelessNetworks(CNetworkInterface* interface)
{
   // Clear the list first
   {
      CGUIMessage msgReset(GUI_MSG_LABEL_RESET, GetID(), CONTROL_WIRELESS);
      OnMessage(msgReset);
   }
   
   m_networkItems.clear(); 
   m_aps.clear();
      
   CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
   pDlgProgress->SetHeading("");
   pDlgProgress->SetLine(0, "Searching for wireless networks...");
   pDlgProgress->SetLine(1, "");
   pDlgProgress->SetLine(2, "");
   pDlgProgress->StartModal();
   pDlgProgress->Progress();

   // Get the list of access points. Try this 3 times if you get an empty list
   int retryCount = 0;
   while (m_aps.size() == 0 && retryCount < 3)
   {
     m_aps = interface->GetAccessPoints();
     retryCount++;
   }

   pDlgProgress->Close();
   
   CStdString currentEssId = interface->GetCurrentWirelessEssId();
   int iSelectedItem = -1;
   
   for (unsigned int i = 0; i < m_aps.size(); i++)
   {
      CFileItemPtr item ( new CFileItem(m_aps[i].getEssId()) );
      
      int q = m_aps[i].getQuality();
      if (q <= 25) item->SetIconImage("wizard_wireless_icon_1.png");
      else if (q <= 50) item->SetIconImage("wizard_wireless_icon_2.png");
      else if (q <= 75) item->SetIconImage("wizard_wireless_icon_3.png");
      else if (q <= 100) item->SetIconImage("wizard_wireless_icon_4.png");

      if (m_aps[i].getEncryptionMode() != ENC_NONE)      
         item->SetThumbnailImage("wizard_lock_icon.png");

      CGUIMessage msg(GUI_MSG_LABEL_ADD, GetID(), CONTROL_WIRELESS, 0, 0, item);
      OnMessage(msg);            

      m_networkItems.push_back(item);
      
      if (m_aps[i].getEssId() == currentEssId)
        iSelectedItem = i;              
   }

   // If the current essid was not found in the scanned list, add it as "Other"   
   if (iSelectedItem == -1 && currentEssId != "")
   {
      CFileItemPtr item ( new CFileItem(currentEssId) );
      item->SetIconImage("button_keyboard_off.png");
      CGUIMessage msg(GUI_MSG_LABEL_ADD, GetID(), CONTROL_WIRELESS, 0, 0, item);
      OnMessage(msg);
      m_networkItems.push_back(item);
      iSelectedItem = m_aps.size();
   }
   else
   {
      CFileItemPtr item ( new CFileItem("Other...") );
      item->SetIconImage("button_keyboard_off.png");
      CGUIMessage msg(GUI_MSG_LABEL_ADD, GetID(), CONTROL_WIRELESS, 0, 0, item);
      OnMessage(msg);
      m_networkItems.push_back(item);
      if (iSelectedItem == -1)
         iSelectedItem = 0;
   }
   
   {
      CGUIMessage msg(GUI_MSG_ITEM_SELECT, GetID(), CONTROL_WIRELESS, iSelectedItem);
      OnMessage(msg);
   }            
   
   CONTROL_DISABLE(CONTROL_NEXT);   
}
Example #9
0
bool CFileShoutcast::Open(const CURL& url, bool bBinary)
{
  m_dwLastTime = timeGetTime();
  int ret;

  CGUIDialogProgress* dlgProgress = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);

  set_rip_manager_options_defaults(&m_opt);

  strcpy(m_opt.output_directory, "./");
  m_opt.proxyurl[0] = '\0';

  // Use a proxy, if the GUI was configured as such
  bool bProxyEnabled = g_guiSettings.GetBool("network.usehttpproxy");
  if (bProxyEnabled)
  {
    const CStdString &strProxyServer = g_guiSettings.GetString("network.httpproxyserver");
    const CStdString &strProxyPort = g_guiSettings.GetString("network.httpproxyport");
	  // Should we check for valid strings here
#ifndef _LINUX
	  _snprintf( m_opt.proxyurl, MAX_URL_LEN, "http://%s:%s", strProxyServer.c_str(), strProxyPort.c_str() );
#else
	  snprintf( m_opt.proxyurl, MAX_URL_LEN, "http://%s:%s", strProxyServer.c_str(), strProxyPort.c_str() );
#endif
  }

  CStdString strUrl;
  url.GetURL(strUrl);
  strUrl.Replace("shout://", "http://");
  printf("Opening url: %s\n", strUrl.c_str());
  strncpy(m_opt.url, strUrl.c_str(), MAX_URL_LEN);
  sprintf(m_opt.useragent, "x%s", url.GetFileName().c_str());
  if (dlgProgress)
  {
    dlgProgress->SetHeading(260);
    dlgProgress->SetLine(0, 259);
    dlgProgress->SetLine(1, strUrl);
    dlgProgress->SetLine(2, "");
    if (!dlgProgress->IsDialogRunning())
      dlgProgress->StartModal();
    dlgProgress->Progress();
  }

  if ((ret = rip_manager_start(rip_callback, &m_opt)) != SR_SUCCESS)
  {
    if (dlgProgress) dlgProgress->Close();
    return false;
  }
  int iShoutcastTimeout = 10 * SHOUTCASTTIMEOUT; //i.e: 10 * 10 = 100 * 100ms = 10s
  int iCount = 0;
  while (!m_fileState.bRipDone && !m_fileState.bRipStarted && !m_fileState.bRipError && (!dlgProgress || !dlgProgress->IsCanceled()))
  {
    if (iCount <= iShoutcastTimeout) //Normally, this isn't the problem,
      //because if RIP_MANAGER fails, this would be here
      //with m_fileState.bRipError
    {
      Sleep(100);
    }
    else
    {
      if (dlgProgress)
      {
        dlgProgress->SetLine(1, 257);
        dlgProgress->SetLine(2, "Connection timed out...");
        Sleep(1500);
        dlgProgress->Close();
      }
      return false;
    }
    iCount++;
  }
  
  if (dlgProgress && dlgProgress->IsCanceled())
  {
     Close();
     dlgProgress->Close();
     return false;
  }

  /* store content type of stream */
  m_contenttype = rip_manager_get_content_type();

  //CHANGED CODE: Don't reset timer anymore.

  while (!m_fileState.bRipDone && !m_fileState.bRipError && m_fileState.bBuffering && (!dlgProgress || !dlgProgress->IsCanceled()))
  {
    if (iCount <= iShoutcastTimeout) //Here is the real problem: Sometimes the buffer fills just to
      //slowly, thus the quality of the stream will be bad, and should be
      //aborted...
    {
      Sleep(100);
      char szTmp[1024];
      //g_dialog.SetCaption(0, "Shoutcast" );
      sprintf(szTmp, "Buffering %i bytes", m_ringbuf.GetMaxReadSize());
      if (dlgProgress)
      {
        dlgProgress->SetLine(2, szTmp );
        dlgProgress->Progress();
      }

      sprintf(szTmp, "%s", m_ripInfo.filename);
      for (int i = 0; i < (int)strlen(szTmp); i++)
        szTmp[i] = tolower((unsigned char)szTmp[i]);
      szTmp[50] = 0;
      if (dlgProgress)
      {
        dlgProgress->SetLine(1, szTmp );
        dlgProgress->Progress();
      }
    }
    else //it's not really a connection timeout, but it's here,
      //where things get boring, if connection is slow.
      //trust me, i did a lot of testing... Doesn't happen often,
      //but if it does it sucks to wait here forever.
      //CHANGED: Other message here
    {
      if (dlgProgress)
      {
        dlgProgress->SetLine(1, 257);
        dlgProgress->SetLine(2, "Connection to server too slow...");
        dlgProgress->Close();
      }
      return false;
    }
    iCount++;
  }
  if (dlgProgress && dlgProgress->IsCanceled())
  {
     Close();
     dlgProgress->Close();
     return false;
  }
  if ( m_fileState.bRipError )
  {
    if (dlgProgress)
    {
      dlgProgress->SetLine(1, 257);
      dlgProgress->SetLine(2, m_errorInfo.error_str);
      dlgProgress->Progress();

      Sleep(1500);
      dlgProgress->Close();
    }
    return false;
  }
  if (dlgProgress)
  {
    dlgProgress->SetLine(2, 261);
    dlgProgress->Progress();
    dlgProgress->Close();
  }
  return true;
}
Example #10
0
bool CCDDARipJob::DoWork()
{
  CLog::Log(LOGINFO, "Start ripping track %s to %s", m_input.c_str(),
                                                     m_output.c_str());

  // if we are ripping to a samba share, rip it to hd first and then copy it it the share
  CFileItem file(m_output, false);
  if (file.IsRemote())
    m_output = SetupTempFile();
  
  if (m_output.IsEmpty())
  {
    CLog::Log(LOGERROR, "CCDDARipper: Error opening file");
    return false;
  }

  // init ripper
  CFile reader;
  CEncoder* encoder;
  if (!reader.Open(m_input,READ_CACHED) || !(encoder=SetupEncoder(reader)))
  {
    CLog::Log(LOGERROR, "Error: CCDDARipper::Init failed");
    return false;
  }

  // setup the progress dialog
  CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  CStdString strLine0, strLine1;
  int iTrack = atoi(m_input.substr(13, m_input.size() - 13 - 5).c_str());
  strLine0.Format("%s %i", g_localizeStrings.Get(606).c_str(), iTrack); // Track Number: %i
  strLine1.Format("%s %s", g_localizeStrings.Get(607).c_str(), m_output.c_str()); // To: %s
  pDlgProgress->SetHeading(605); // Ripping
  pDlgProgress->SetLine(0, strLine0);
  pDlgProgress->SetLine(1, strLine1);
  pDlgProgress->SetLine(2, "");
  pDlgProgress->StartModal();
  pDlgProgress->ShowProgressBar(true);

  // show progress dialog
  pDlgProgress->Progress();

  // start ripping
  int percent=0;
  int oldpercent=0;
  bool cancelled(false);
  int result;
  while (!cancelled && (result=RipChunk(reader, encoder, percent)) == 0)
  {
    cancelled = ShouldCancel(percent,100);
    cancelled |= pDlgProgress->IsCanceled();
    if (percent > oldpercent)
    {
      oldpercent = percent;
      pDlgProgress->SetPercentage(percent);
      pDlgProgress->Progress();
    }
  }

  pDlgProgress->Close();

  // close encoder ripper
  encoder->Close();
  delete encoder;
  reader.Close();

  if (file.IsRemote() && !cancelled && result == 2)
  {
    // copy the ripped track to the share
    if (!CFile::Cache(m_output, file.GetPath()))
    {
      CLog::Log(LOGERROR, "CDDARipper: Error copying file from %s to %s", 
                m_output.c_str(), file.GetPath().c_str());
      CFile::Delete(m_output);
      return false;
    }
    // delete cached file
    CFile::Delete(m_output);
  }

  if (cancelled)
  {
    CLog::Log(LOGWARNING, "User Cancelled CDDA Rip");
    CFile::Delete(m_output);
  }
  else if (result == 1)
    CLog::Log(LOGERROR, "CDDARipper: Error ripping %s", m_input.c_str());
  else if (result < 0)
    CLog::Log(LOGERROR, "CDDARipper: Error encoding %s", m_input.c_str());
  else
  {
    CLog::Log(LOGINFO, "Finished ripping %s", m_input.c_str());
    if (m_eject)
    {
      CLog::Log(LOGINFO, "Ejecting CD");
      g_mediaManager.EjectTray();
    }
  }

  return !cancelled && result == 2;
}
Example #11
0
bool CPluginDirectory::WaitOnScriptResult(const std::string &scriptPath, int scriptId, const std::string &scriptName, bool retrievingDir)
{
  const unsigned int timeBeforeProgressBar = 1500;
  const unsigned int timeToKillScript = 1000;

  unsigned int startTime = XbmcThreads::SystemClockMillis();
  CGUIDialogProgress *progressBar = NULL;
  bool cancelled = false;
  bool inMainAppThread = g_application.IsCurrentThread();

  CLog::Log(LOGDEBUG, "%s - waiting on the %s (id=%d) plugin...", __FUNCTION__, scriptName.c_str(), scriptId);
  while (true)
  {
    {
      CSingleExit ex(g_graphicsContext);
      // check if the python script is finished
      if (m_fetchComplete.WaitMSec(20))
      { // python has returned
        CLog::Log(LOGDEBUG, "%s- plugin returned %s", __FUNCTION__, m_success ? "successfully" : "failure");
        break;
      }
    }
    // check our script is still running
    if (!CScriptInvocationManager::Get().IsRunning(scriptId))
    { // check whether we exited normally
      if (!m_fetchComplete.WaitMSec(0))
      { // python didn't return correctly
        CLog::Log(LOGDEBUG, " %s - plugin exited prematurely - terminating", __FUNCTION__);
        m_success = false;
      }
      break;
    }

    // check whether we should pop up the progress dialog
    if (!retrievingDir && !progressBar && XbmcThreads::SystemClockMillis() - startTime > timeBeforeProgressBar)
    { // loading takes more then 1.5 secs, show a progress dialog
      progressBar = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);

      // if script has shown progressbar don't override it
      if (progressBar && progressBar->IsActive())
      {
        startTime = XbmcThreads::SystemClockMillis();
        progressBar = NULL;
      }

      if (progressBar)
      {
        progressBar->SetHeading(CVariant{scriptName});
        progressBar->SetLine(0, CVariant{10214});
        progressBar->SetLine(1, CVariant{""});
        progressBar->SetLine(2, CVariant{""});
        progressBar->ShowProgressBar(false);
        progressBar->Open();
      }
    }

    if (progressBar)
    { // update the progress bar and check for user cancel
      progressBar->Progress();
      if (progressBar->IsCanceled())
      { // user has cancelled our process - cancel our process
        m_cancelled = true;
      }
    }
    else // if the progressBar exists and we call StartModal or Progress we get the
         //  ProcessRenderLoop call anyway.
      if (inMainAppThread) 
        g_windowManager.ProcessRenderLoop();

    if (!cancelled && m_cancelled)
    {
      cancelled = true;
      startTime = XbmcThreads::SystemClockMillis();
    }
    if ((cancelled && XbmcThreads::SystemClockMillis() - startTime > timeToKillScript) || g_application.m_bStop)
    { // cancel our script
      if (scriptId != -1 && CScriptInvocationManager::Get().IsRunning(scriptId))
      {
        CLog::Log(LOGDEBUG, "%s- cancelling plugin %s (id=%d)", __FUNCTION__, scriptName.c_str(), scriptId);
        CScriptInvocationManager::Get().Stop(scriptId);
        break;
      }
    }
  }

  if (progressBar)
    CApplicationMessenger::Get().PostMsg(TMSG_GUI_WINDOW_CLOSE, -1, 0, static_cast<void*>(progressBar));

  return !cancelled && m_success;
}
bool CPluginDirectory::WaitOnScriptResult(const CStdString &scriptPath, const CStdString &scriptName, bool retrievingDir)
{
  const unsigned int timeBeforeProgressBar = 1500;
  const unsigned int timeToKillScript = 1000;

  unsigned int startTime = CTimeUtils::GetTimeMS();
  CGUIDialogProgress *progressBar = NULL;

  CLog::Log(LOGDEBUG, "%s - waiting on the %s plugin...", __FUNCTION__, scriptName.c_str());
  while (true)
  {
    CSingleExit ex(g_graphicsContext);
    // check if the python script is finished
    if (WaitForSingleObject(m_fetchComplete, 20) == WAIT_OBJECT_0)
    { // python has returned
      CLog::Log(LOGDEBUG, "%s- plugin returned %s", __FUNCTION__, m_success ? "successfully" : "failure");
      break;
    }
    ex.Restore();

    // check our script is still running
#ifdef HAS_PYTHON
    if (!g_pythonParser.isRunning(g_pythonParser.getScriptId(scriptPath.c_str())))
#endif
    { // check whether we exited normally
      if (WaitForSingleObject(m_fetchComplete, 0) == WAIT_TIMEOUT)
      { // python didn't return correctly
        CLog::Log(LOGDEBUG, " %s - plugin exited prematurely - terminating", __FUNCTION__);
        m_success = false;
      }
      break;
    }

    // check whether we should pop up the progress dialog
    if (!progressBar && CTimeUtils::GetTimeMS() - startTime > timeBeforeProgressBar)
    { // loading takes more then 1.5 secs, show a progress dialog
      progressBar = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);

      // if script has shown progressbar don't override it
      if (progressBar && progressBar->IsActive())
      {
        startTime = CTimeUtils::GetTimeMS();
        progressBar = NULL;
      }

      if (progressBar)
      {
        progressBar->SetHeading(scriptName);
        progressBar->SetLine(0, retrievingDir ? 1040 : 10214);
        progressBar->SetLine(1, "");
        progressBar->SetLine(2, "");
        progressBar->ShowProgressBar(retrievingDir);
        progressBar->StartModal();
      }
    }

    if (progressBar)
    { // update the progress bar and check for user cancel
      if (retrievingDir)
      {
        CStdString label;
        if (m_totalItems > 0)
        {
          label.Format(g_localizeStrings.Get(1042).c_str(), m_listItems->Size(), m_totalItems);
          progressBar->SetPercentage((int)((m_listItems->Size() * 100 ) / m_totalItems));
          progressBar->ShowProgressBar(true);
        }
        else
          label.Format(g_localizeStrings.Get(1041).c_str(), m_listItems->Size());
        progressBar->SetLine(2, label);
      }
      progressBar->Progress();
      if (progressBar->IsCanceled())
      { // user has cancelled our process - cancel our process
        if (!m_cancelled)
        {
          m_cancelled = true;
          startTime = CTimeUtils::GetTimeMS();
        }
        if (m_cancelled && CTimeUtils::GetTimeMS() - startTime > timeToKillScript)
        { // cancel our script
#ifdef HAS_PYTHON
          int id = g_pythonParser.getScriptId(scriptPath.c_str());
          if (id != -1 && g_pythonParser.isRunning(id))
          {
            CLog::Log(LOGDEBUG, "%s- cancelling plugin %s", __FUNCTION__, scriptName.c_str());
            g_pythonParser.stopScript(id);
            break;
          }
#endif
        }
      }
    }
  }
  if (progressBar)
    g_application.getApplicationMessenger().Close(progressBar, false, false);

  return !m_cancelled && m_success;
}
Example #13
0
void CGUIWindowFileManager::OnPopupMenu(int list, int item, bool bContextDriven /* = true */)
{
  if (list < 0 || list >= 2) return ;
  bool bDeselect = SelectItem(list, item);
  // calculate the position for our menu
  float posX = 200;
  float posY = 100;
  const CGUIControl *pList = GetControl(CONTROL_LEFT_LIST + list);
  if (pList)
  {
    posX = pList->GetXPosition() + pList->GetWidth() / 2;
    posY = pList->GetYPosition() + pList->GetHeight() / 2;
  }

  CFileItemPtr pItem = m_vecItems[list]->Get(item);
  if (!pItem.get())
    return;

  if (m_Directory[list]->IsVirtualDirectoryRoot())
  {
    if (item < 0)
    { //! @todo We should add the option here for shares to be added if there aren't any
      return ;
    }

    // and do the popup menu
    if (CGUIDialogContextMenu::SourcesMenu("files", pItem, posX, posY))
    {
      m_rootDir.SetSources(*CMediaSourceSettings::GetInstance().GetSources("files"));
      if (m_Directory[1 - list]->IsVirtualDirectoryRoot())
        Refresh();
      else
        Refresh(list);
      return ;
    }
    pItem->Select(false);
    return ;
  }
  // popup the context menu

  bool showEntry = false;
  if (item >= m_vecItems[list]->Size()) item = -1;
  if (item >= 0)
    showEntry=(!pItem->IsParentFolder() || (pItem->IsParentFolder() && m_vecItems[list]->GetSelectedCount()>0));

  // determine available players
  std::vector<std::string>players;
  CPlayerCoreFactory::GetInstance().GetPlayers(*pItem, players);

  // add the needed buttons
  CContextButtons choices;
  if (item >= 0)
  {
    //The ".." item is not selectable. Take that into account when figuring out if all items are selected
    int notSelectable = CServiceBroker::GetSettings().GetBool(CSettings::SETTING_FILELISTS_SHOWPARENTDIRITEMS) ? 1 : 0;
    if (NumSelected(list) <  m_vecItems[list]->Size() - notSelectable)
      choices.Add(CONTROL_BTNSELECTALL, 188); // SelectAll
    if (!pItem->IsParentFolder())
      choices.Add(CONTROL_BTNFAVOURITES, CServiceBroker::GetFavouritesService().IsFavourited(*pItem.get(), GetID()) ? 14077 : 14076); // Add/Remove Favourite
    if (players.size() > 1)
      choices.Add(CONTROL_BTNPLAYWITH, 15213);
    if (CanRename(list) && !pItem->IsParentFolder())
      choices.Add(CONTROL_BTNRENAME, 118);
    if (CanDelete(list) && showEntry)
      choices.Add(CONTROL_BTNDELETE, 117);
    if (CanCopy(list) && showEntry)
      choices.Add(CONTROL_BTNCOPY, 115);
    if (CanMove(list) && showEntry)
      choices.Add(CONTROL_BTNMOVE, 116);
  }
  if (CanNewFolder(list))
    choices.Add(CONTROL_BTNNEWFOLDER, 20309);
  if (item >= 0 && pItem->m_bIsFolder && !pItem->IsParentFolder())
    choices.Add(CONTROL_BTNCALCSIZE, 13393);
  choices.Add(CONTROL_BTNSWITCHMEDIA, 523);
  if (CJobManager::GetInstance().IsProcessing("filemanager"))
    choices.Add(CONTROL_BTNCANCELJOB, 167);

  if (!pItem->m_bIsFolder)
    choices.Add(CONTROL_BTNVIEW, 39104);

  int btnid = CGUIDialogContextMenu::ShowAndGetChoice(choices);
  if (btnid == CONTROL_BTNSELECTALL)
  {
    OnSelectAll(list);
    bDeselect=false;
  }
  if (btnid == CONTROL_BTNFAVOURITES)
  {
    CServiceBroker::GetFavouritesService().AddOrRemove(*pItem.get(), GetID());
    return;
  }
  if (btnid == CONTROL_BTNPLAYWITH)
  {
    std::vector<std::string>players;
    CPlayerCoreFactory::GetInstance().GetPlayers(*pItem, players);
    std::string player = CPlayerCoreFactory::GetInstance().SelectPlayerDialog(players);
    if (!player.empty())
      OnStart(pItem.get(), player);
  }
  if (btnid == CONTROL_BTNRENAME)
    OnRename(list);
  if (btnid == CONTROL_BTNDELETE)
    OnDelete(list);
  if (btnid == CONTROL_BTNCOPY)
    OnCopy(list);
  if (btnid == CONTROL_BTNMOVE)
    OnMove(list);
  if (btnid == CONTROL_BTNNEWFOLDER)
    OnNewFolder(list);
  if (btnid == CONTROL_BTNCALCSIZE)
  {
    // setup the progress dialog, and show it
    CGUIDialogProgress *progress = g_windowManager.GetWindow<CGUIDialogProgress>(WINDOW_DIALOG_PROGRESS);
    if (progress)
    {
      progress->SetHeading(CVariant{13394});
      for (int i=0; i < 3; i++)
        progress->SetLine(i, CVariant{""});
      progress->Open();
    }

    //  Calculate folder size for each selected item
    for (int i=0; i<m_vecItems[list]->Size(); ++i)
    {
      CFileItemPtr pItem2=m_vecItems[list]->Get(i);
      if (pItem2->m_bIsFolder && pItem2->IsSelected())
      {
        int64_t folderSize = CalculateFolderSize(pItem2->GetPath(), progress);
        if (folderSize >= 0)
        {
          pItem2->m_dwSize = folderSize;
          if (folderSize == 0)
            pItem2->SetLabel2(StringUtils::SizeToString(folderSize));
          else
            pItem2->SetFileSizeLabel();
        }
      }
    }
    if (progress)
      progress->Close();
  }
  if (btnid == CONTROL_BTNSWITCHMEDIA)
  {
    CGUIDialogContextMenu::SwitchMedia("files", m_vecItems[list]->GetPath());
    return;
  }
  if (btnid == CONTROL_BTNCANCELJOB)
    CancelJobs();
  if (btnid == CONTROL_BTNVIEW)
    CGUIDialogTextViewer::ShowForFile(pItem->GetPath(), true);

  if (bDeselect && item >= 0 && item < m_vecItems[list]->Size())
  { // deselect item as we didn't do anything
    pItem->Select(false);
  }
}
Example #14
0
bool CShoutcastDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CStdString strRoot = strPath;
  if (CUtil::HasSlashAtEnd(strRoot) && strRoot != "shout://")
    strRoot.Delete(strRoot.size() - 1);

  /* keep backward competability (for users who already have this source defined) */
  if( strRoot.Equals("shout://www.shoutcast.com") || strRoot.Equals("shout://") || strRoot.Equals("shout://classic.shoutcast.com") || 
      strRoot.Equals("shout://www.shoutcast.com/sbin/newxml.phtml") )
    strRoot = SHOUTCAST_MASTER_LINK;

  CGUIDialogProgress* dlgProgress = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  if (dlgProgress)
  {
    dlgProgress->ShowProgressBar(false);
    dlgProgress->SetHeading(260);
    dlgProgress->SetLine(0, 14003);
    dlgProgress->SetLine(1, "");
    dlgProgress->SetLine(2, "");
    dlgProgress->StartModal();
  }

  CURL url(strRoot);
  CStdString protocol = url.GetProtocol();
  url.SetProtocol("http");

  CFileCurl http;

  //CURL doesn't seem to understand that data is encoded.. odd
  // opening as text for now
  //http.SetContentEncoding("deflate");

  if( !http.Open(url, false) ) 
  {
    CLog::Log(LOGERROR, "%s - Unable to get shoutcast dir", __FUNCTION__);
    if (dlgProgress) dlgProgress->Close();
    return false;
  }

  /* restore protocol */
  url.SetProtocol(protocol);

  CStdString content = http.GetContent();
  if( !(content.Equals("text/html") || content.Equals("text/xml") 
	  || content.Equals("text/html;charset=utf-8") || content.Equals("text/xml;charset=utf-8") ))
  {
    CLog::Log(LOGERROR, "%s - Invalid content type %s", __FUNCTION__, content.c_str());
    if (dlgProgress) dlgProgress->Close();
    return false;
  }
  
  
  int size_read = 0;  
  int size_total = (int)http.GetLength();
  int data_size = 0;

  CStdString data;
  data.reserve(size_total);
  
  /* read response from server into string buffer */
  char buffer[16384];
  while( (size_read = http.Read(buffer, sizeof(buffer)-1)) > 0 )
  {
    buffer[size_read] = 0;
    data += buffer;
    data_size += size_read;

    dlgProgress->Progress();

    if (dlgProgress->IsCanceled())
    {
      dlgProgress->Close();
      return false;
    }
  }

  /* parse returned xml */
  TiXmlDocument doc;
  doc.Parse(data.c_str());

  TiXmlElement *root = doc.RootElement();
  if(root == NULL)
  {
    CLog::Log(LOGERROR, "%s - Unable to parse xml", __FUNCTION__);
    CLog::Log(LOGDEBUG, "%s - Sample follows...\n%s", __FUNCTION__, data.c_str());

    dlgProgress->Close();
    return false;
  }

  /* clear data to keep memusage down, not needed anymore */
  data.Empty();

  bool result = false;
  if( strcmp(root->Value(), "genrelist") == 0 )
    result = ParseGenres(root, items, url);
  else if( strcmp(root->Value(), "stationlist") == 0 )
    result = ParseStations(root, items, url);
  else
  {
    CLog::Log(LOGERROR, "%s - Invalid root xml element for shoutcast",__FUNCTION__);
    CLog::Log(LOGDEBUG, "%s - Sample follows...\n%s", __FUNCTION__, data.c_str());
  }

  if (dlgProgress) dlgProgress->Close();
  return result;
}
Example #15
0
bool CMultiPathDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
  CLog::Log(LOGDEBUG,"CMultiPathDirectory::GetDirectory(%s)", strPath.c_str());

  vector<CStdString> vecPaths;
  if (!GetPaths(strPath, vecPaths))
    return false;

  XbmcThreads::EndTime progressTime(3000); // 3 seconds before showing progress bar
  CGUIDialogProgress* dlgProgress = NULL;

  unsigned int iFailures = 0;
  for (unsigned int i = 0; i < vecPaths.size(); ++i)
  {
    // show the progress dialog if we have passed our time limit
    if (progressTime.IsTimePast() && !dlgProgress)
    {
      dlgProgress = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
      if (dlgProgress)
      {
        dlgProgress->SetHeading(15310);
        dlgProgress->SetLine(0, 15311);
        dlgProgress->SetLine(1, "");
        dlgProgress->SetLine(2, "");
        dlgProgress->StartModal();
        dlgProgress->ShowProgressBar(true);
        dlgProgress->SetProgressMax((int)vecPaths.size()*2);
        dlgProgress->Progress();
      }
    }
    if (dlgProgress)
    {
      CURL url(vecPaths[i]);
      dlgProgress->SetLine(1, url.GetWithoutUserDetails());
      dlgProgress->SetProgressAdvance();
      dlgProgress->Progress();
    }

    CFileItemList tempItems;
    CLog::Log(LOGDEBUG,"Getting Directory (%s)", vecPaths[i].c_str());
    if (CDirectory::GetDirectory(vecPaths[i], tempItems, m_strFileMask, m_flags))
      items.Append(tempItems);
    else
    {
      CLog::Log(LOGERROR,"Error Getting Directory (%s)", vecPaths[i].c_str());
      iFailures++;
    }

    if (dlgProgress)
    {
      dlgProgress->SetProgressAdvance();
      dlgProgress->Progress();
    }
  }

  if (dlgProgress)
    dlgProgress->Close();

  if (iFailures == vecPaths.size())
    return false;

  // merge like-named folders into a sub multipath:// style url
  MergeItems(items);

  return true;
}
Example #16
0
bool CPluginDirectory::WaitOnScriptResult(const CStdString &scriptPath, const CStdString &scriptName, bool retrievingDir)
{
  const unsigned int timeBeforeProgressBar = 1500;
  const unsigned int timeToKillScript = 1000;

  unsigned int startTime = XbmcThreads::SystemClockMillis();
  CGUIDialogProgress *progressBar = NULL;
  bool cancelled = false;

  CLog::Log(LOGDEBUG, "%s - waiting on the %s plugin...", __FUNCTION__, scriptName.c_str());
  while (true)
  {
    {
      CSingleExit ex(g_graphicsContext);
      // check if the python script is finished
      if (m_fetchComplete.WaitMSec(20))
      { // python has returned
        CLog::Log(LOGDEBUG, "%s- plugin returned %s", __FUNCTION__, m_success ? "successfully" : "failure");
        break;
      }
    }
    // check our script is still running
#ifdef HAS_PYTHON
    if (!g_pythonParser.isRunning(g_pythonParser.getScriptId(scriptPath.c_str())))
#endif
    { // check whether we exited normally
      if (!m_fetchComplete.WaitMSec(0))
      { // python didn't return correctly
        CLog::Log(LOGDEBUG, " %s - plugin exited prematurely - terminating", __FUNCTION__);
        m_success = false;
      }
      break;
    }

    // check whether we should pop up the progress dialog
    if (!retrievingDir && !progressBar && XbmcThreads::SystemClockMillis() - startTime > timeBeforeProgressBar)
    { // loading takes more then 1.5 secs, show a progress dialog
      progressBar = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);

      // if script has shown progressbar don't override it
      if (progressBar && progressBar->IsActive())
      {
        startTime = XbmcThreads::SystemClockMillis();
        progressBar = NULL;
      }

      if (progressBar)
      {
        progressBar->SetHeading(scriptName);
        progressBar->SetLine(0, retrievingDir ? 1040 : 10214);
        progressBar->SetLine(1, "");
        progressBar->SetLine(2, "");
        progressBar->ShowProgressBar(retrievingDir);
        progressBar->StartModal();
      }
    }

    if (progressBar)
    { // update the progress bar and check for user cancel
      progressBar->Progress();
      if (progressBar->IsCanceled())
      { // user has cancelled our process - cancel our process
        m_cancelled = true;
      }
    }
    if (!cancelled && m_cancelled)
    {
      cancelled = true;
      startTime = XbmcThreads::SystemClockMillis();
    }
    if (cancelled && XbmcThreads::SystemClockMillis() - startTime > timeToKillScript)
    { // cancel our script
#ifdef HAS_PYTHON
      int id = g_pythonParser.getScriptId(scriptPath.c_str());
      if (id != -1 && g_pythonParser.isRunning(id))
      {
        CLog::Log(LOGDEBUG, "%s- cancelling plugin %s", __FUNCTION__, scriptName.c_str());
        g_pythonParser.stopScript(id);
        break;
      }
#endif
    }
  }

  if (progressBar)
    CApplicationMessenger::Get().Close(progressBar, false, false);

  return !cancelled && m_success;
}
Example #17
0
bool CPluginDirectory::WaitOnScriptResult(const CStdString &scriptPath, const CStdString &scriptName)
{
  const unsigned int timeBeforeProgressBar = 1500;
  const unsigned int timeToKillScript = 1000;

  DWORD startTime = timeGetTime();
  CGUIDialogProgress *progressBar = NULL;

  CLog::Log(LOGDEBUG, "%s - waiting on the %s plugin...", __FUNCTION__, scriptName.c_str());
  while (true)
  {
    // check if the python script is finished
    if (WaitForSingleObject(m_directoryFetched, 20) == WAIT_OBJECT_0)
    { // python has returned
      CLog::Log(LOGDEBUG, "%s- plugin returned %s", __FUNCTION__, m_success ? "successfully" : "failure");
      break;
    }
    // check our script is still running
    int id = g_pythonParser.getScriptId(scriptPath.c_str());
    if (id == -1)
    { // nope - bail
      CLog::Log(LOGDEBUG, " %s - plugin exited prematurely - terminating", __FUNCTION__);
      m_success = false;
      break;
    }

    // check whether we should pop up the progress dialog
    if (!progressBar && timeGetTime() - startTime > timeBeforeProgressBar)
    { // loading takes more then 1.5 secs, show a progress dialog
      progressBar = (CGUIDialogProgress *)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
      if (progressBar)
      {
        progressBar->SetHeading(scriptName);
        progressBar->SetLine(0, 1040);
        progressBar->SetLine(1, "");
        progressBar->SetLine(2, "");
        progressBar->StartModal();
      }
    }

    if (progressBar)
    { // update the progress bar and check for user cancel
      CStdString label;
      if (m_totalItems > 0)
      {
        label.Format(g_localizeStrings.Get(1042).c_str(), m_listItems->Size(), m_totalItems);
        progressBar->SetPercentage((int)((m_listItems->Size() * 100 ) / m_totalItems));
        progressBar->ShowProgressBar(true);
      }
      else
        label.Format(g_localizeStrings.Get(1041).c_str(), m_listItems->Size());
      progressBar->SetLine(2, label);
      progressBar->Progress();
      if (progressBar->IsCanceled())
      { // user has cancelled our process - cancel our process
        if (!m_cancelled)
        {
          m_cancelled = true;
          startTime = timeGetTime();
        }
        if (m_cancelled && timeGetTime() - startTime > timeToKillScript)
        { // cancel our script
          int id = g_pythonParser.getScriptId(scriptPath.c_str());
          if (id != -1 && g_pythonParser.isRunning(id))
          {
            CLog::Log(LOGDEBUG, "%s- cancelling plugin %s", __FUNCTION__, scriptName.c_str());
            g_pythonParser.stopScript(id);
            break;
          }
        }
      }
    }
  }
  if (progressBar)
    progressBar->Close();

  return !m_cancelled && m_success;
}
Example #18
0
bool CPartyModeManager::Enable(PartyModeContext context /*= PARTYMODECONTEXT_MUSIC*/, const std::string& strXspPath /*= ""*/)
{
  // Filter using our PartyMode xml file
  CSmartPlaylist playlist;
  std::string partyModePath;
  bool playlistLoaded;

  m_bIsVideo = context == PARTYMODECONTEXT_VIDEO;
  if (!strXspPath.empty()) //if a path to a smartplaylist is supplied use it
    partyModePath = strXspPath;
  else if (m_bIsVideo)
    partyModePath = CProfilesManager::Get().GetUserDataItem("PartyMode-Video.xsp");
  else
    partyModePath = CProfilesManager::Get().GetUserDataItem("PartyMode.xsp");

  playlistLoaded=playlist.Load(partyModePath);

  if ( playlistLoaded )
  {
    m_type = playlist.GetType();
    if (context == PARTYMODECONTEXT_UNKNOWN)
    {
      //get it from the xsp file
      m_bIsVideo = (StringUtils::EqualsNoCase(m_type, "video") ||
                    StringUtils::EqualsNoCase(m_type, "musicvideos") ||
                    StringUtils::EqualsNoCase(m_type, "mixed"));
    }

    if (StringUtils::EqualsNoCase(m_type, "mixed"))
      playlist.SetType("songs");

    if (StringUtils::EqualsNoCase(m_type, "mixed"))
      playlist.SetType("video");

    playlist.SetType(m_type);
  }
  else
  {
    m_strCurrentFilterMusic.clear();
    m_strCurrentFilterVideo.clear();
    m_type = m_bIsVideo ? "musicvideos" : "songs";
  }

  CGUIDialogProgress* pDialog = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  int iHeading = (m_bIsVideo ? 20250 : 20121);
  int iLine0 = (m_bIsVideo ? 20251 : 20123);
  pDialog->SetHeading(CVariant{iHeading});
  pDialog->SetLine(0, CVariant{iLine0});
  pDialog->SetLine(1, CVariant{""});
  pDialog->SetLine(2, CVariant{""});
  pDialog->Open();

  ClearState();
  unsigned int time = XbmcThreads::SystemClockMillis();
  vector< pair<int,int> > songIDs;
  if (StringUtils::EqualsNoCase(m_type, "songs") ||
      StringUtils::EqualsNoCase(m_type, "mixed"))
  {
    CMusicDatabase db;
    if (db.Open())
    {
      set<std::string> playlists;
      if ( playlistLoaded )
        m_strCurrentFilterMusic = playlist.GetWhereClause(db, playlists);

      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterMusic.c_str());
      m_iMatchingSongs = (int)db.GetSongIDs(m_strCurrentFilterMusic, songIDs);
      if (m_iMatchingSongs < 1 && StringUtils::EqualsNoCase(m_type, "songs"))
      {
        pDialog->Close();
        db.Close();
        OnError(16031, (std::string)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (std::string)"Party mode could not open database. Aborting.");
      return false;
    }
    db.Close();
  }

  if (StringUtils::EqualsNoCase(m_type, "musicvideos") ||
      StringUtils::EqualsNoCase(m_type, "mixed"))
  {
    vector< pair<int,int> > songIDs2;
    CVideoDatabase db;
    if (db.Open())
    {
      set<std::string> playlists;
      if ( playlistLoaded )
        m_strCurrentFilterVideo = playlist.GetWhereClause(db, playlists);

      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterVideo.c_str());
      m_iMatchingSongs += (int)db.GetMusicVideoIDs(m_strCurrentFilterVideo, songIDs2);
      if (m_iMatchingSongs < 1)
      {
        pDialog->Close();
        db.Close();
        OnError(16031, (std::string)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (std::string)"Party mode could not open database. Aborting.");
      return false;
    }
    db.Close();
    songIDs.insert(songIDs.end(),songIDs2.begin(),songIDs2.end());
  }

  // calculate history size
  if (m_iMatchingSongs < 50)
    m_songsInHistory = 0;
  else
    m_songsInHistory = (int)(m_iMatchingSongs/2);
  if (m_songsInHistory > 200)
    m_songsInHistory = 200;

  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Matching songs = %i, History size = %i", m_iMatchingSongs, m_songsInHistory);
  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Party mode enabled!");

  int iPlaylist = m_bIsVideo ? PLAYLIST_VIDEO : PLAYLIST_MUSIC;

  g_playlistPlayer.ClearPlaylist(iPlaylist);
  g_playlistPlayer.SetShuffle(iPlaylist, false);
  g_playlistPlayer.SetRepeat(iPlaylist, PLAYLIST::REPEAT_NONE);

  pDialog->SetLine(0, CVariant{m_bIsVideo ? 20252 : 20124});
  pDialog->Progress();
  // add initial songs
  if (!AddInitialSongs(songIDs))
  {
    pDialog->Close();
    return false;
  }
  CLog::Log(LOGDEBUG, "%s time for song fetch: %u",
            __FUNCTION__, XbmcThreads::SystemClockMillis() - time);

  // start playing
  g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
  Play(0);

  pDialog->Close();
  // open now playing window
  if (StringUtils::EqualsNoCase(m_type, "songs"))
  {
    if (g_windowManager.GetActiveWindow() != WINDOW_MUSIC_PLAYLIST)
      g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST);
  }

  // done
  m_bEnabled = true;
  Announce();
  return true;
}
Example #19
0
bool CPartyModeManager::Enable(PartyModeContext context /*= PARTYMODECONTEXT_MUSIC*/, const CStdString& strXspPath /*= ""*/)
{
  // Filter using our PartyMode xml file
  CSmartPlaylist playlist;
  CStdString partyModePath;

  m_bIsVideo = context == PARTYMODECONTEXT_VIDEO;
  if (!strXspPath.IsEmpty()) //if a path to a smartplaylist is supplied use it
    partyModePath = strXspPath;
  else if (m_bIsVideo)
    partyModePath = g_settings.GetUserDataItem("PartyMode-Video.xsp");
  else
    partyModePath = g_settings.GetUserDataItem("PartyMode.xsp");
  if (playlist.Load(partyModePath))
  {
    m_type = playlist.GetType();
    if (context == PARTYMODECONTEXT_UNKNOWN)
    {
      //get it from the xsp file
      m_bIsVideo = (m_type.Equals("video") || m_type.Equals("mixed"));
    }
    if (m_type.Equals("mixed"))
      playlist.SetType("songs");
    m_strCurrentFilterMusic = playlist.GetWhereClause();
    if (m_type.Equals("mixed"))
      playlist.SetType("video");
    m_strCurrentFilterVideo = playlist.GetWhereClause();
    playlist.SetType(m_type);
  }
  else
  {
    m_strCurrentFilterMusic.Empty();
    m_strCurrentFilterVideo.Empty();
    m_type = m_bIsVideo ? "musicvideos" : "songs";
  }

  CGUIDialogProgress* pDialog = (CGUIDialogProgress*)m_gWindowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  int iHeading = (m_bIsVideo ? 20250 : 20121);
  int iLine0 = (m_bIsVideo ? 20251 : 20123);
  pDialog->SetHeading(iHeading);
  pDialog->SetLine(0, iLine0);
  pDialog->SetLine(1, "");
  pDialog->SetLine(2, "");
  pDialog->StartModal();

  ClearState();
  DWORD time = timeGetTime();
  vector<pair<int,long> > songIDs;
  if (m_type.Equals("songs") || m_type.Equals("mixed"))
  {
    CMusicDatabase musicdatabase;
    if (musicdatabase.Open())
    {
      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterMusic.c_str());
      m_iMatchingSongs = (int)musicdatabase.GetSongIDs(m_strCurrentFilterMusic, songIDs);
      if (m_iMatchingSongs < 1 && m_type.Equals("songs"))
      {
        pDialog->Close();
        musicdatabase.Close();
        OnError(16031, (CStdString)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (CStdString)"Party mode could not open database. Aborting.");
      return false;
    }
    musicdatabase.Close();
  }
  if (m_type.Equals("musicvideos") || m_type.Equals("mixed"))
  {
    vector<pair<int,long> > songIDs2;
    CVideoDatabase database;
    if (database.Open())
    {
      CLog::Log(LOGINFO, "PARTY MODE MANAGER: Registering filter:[%s]", m_strCurrentFilterVideo.c_str());
      m_iMatchingSongs += (int)database.GetMusicVideoIDs(m_strCurrentFilterVideo, songIDs2);
      if (m_iMatchingSongs < 1)
      {
        pDialog->Close();
        database.Close();
        OnError(16031, (CStdString)"Party mode found no matching songs. Aborting.");
        return false;
      }
    }
    else
    {
      pDialog->Close();
      OnError(16033, (CStdString)"Party mode could not open database. Aborting.");
      return false;
    }
    database.Close();
    songIDs.insert(songIDs.end(),songIDs2.begin(),songIDs2.end());
  }

  // calculate history size
  if (m_iMatchingSongs < 50)
    m_songsInHistory = 0;
  else
    m_songsInHistory = (int)(m_iMatchingSongs/2);
  if (m_songsInHistory > 200)
    m_songsInHistory = 200;

  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Matching songs = %i, History size = %i", m_iMatchingSongs, m_songsInHistory);
  CLog::Log(LOGINFO,"PARTY MODE MANAGER: Party mode enabled!");

  int iPlaylist = m_bIsVideo ? PLAYLIST_VIDEO : PLAYLIST_MUSIC;

  g_playlistPlayer.ClearPlaylist(iPlaylist);
  g_playlistPlayer.SetShuffle(iPlaylist, false);
  g_playlistPlayer.SetRepeat(iPlaylist, PLAYLIST::REPEAT_NONE);

  pDialog->SetLine(0, (m_bIsVideo ? 20252 : 20124));
  pDialog->Progress();
  // add initial songs
  if (!AddInitialSongs(songIDs))
  {
    pDialog->Close();
    return false;
  }
  CLog::Log(LOGDEBUG, "%s time for song fetch: %u",
            __FUNCTION__, timeGetTime() - time);

  // start playing
  g_playlistPlayer.SetCurrentPlaylist(iPlaylist);
  Play(0);

  pDialog->Close();
  // open now playing window
  if (m_type.Equals("songs"))
  {
    if (m_gWindowManager.GetActiveWindow() != WINDOW_MUSIC_PLAYLIST)
      m_gWindowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST);
  }

  // done
  m_bEnabled = true;
  return true;
}
void CGUIDialogPVRChannelManager::SaveList() // XXX investigate: renumbering doesn't work
{
  if (!m_bContainsChanges)
   return;

  CPVRDatabase *database = CPVRManager::Get()->GetTVDatabase();
  if (!database || !database->Open())
    return;

  CGUIDialogProgress* pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  pDlgProgress->SetHeading(190);
  pDlgProgress->SetLine(0, "");
  pDlgProgress->SetLine(1, 328);
  pDlgProgress->SetLine(2, "");
  pDlgProgress->StartModal();
  pDlgProgress->Progress();
  pDlgProgress->SetPercentage(0);

  int iActiveChannels = 0;
  for (int iListPtr = 0; iListPtr < m_channelItems->Size(); iListPtr++)
  {
    if (m_channelItems->Get(iListPtr)->GetPropertyBOOL("ActiveChannel"))
      ++iActiveChannels;
  }

//  int iNextChannelNumber = 1;
//  int iNextHiddenChannelNumber = iActiveChannels + 1;
  bool bHasChangedItems = false;

  for (int iListPtr = 0; iListPtr < m_channelItems->Size(); iListPtr++)
  {
    bool bChanged = false;
    CFileItemPtr pItem = m_channelItems->Get(iListPtr);
    if (!pItem)
      continue;
    CPVRChannel *channel = pItem->GetPVRChannelInfoTag();

    if (!channel)
    {
      //TODO add new channel
      continue;
    }

    /* get values from the form */
    bool bHidden              = !pItem->GetPropertyBOOL("ActiveChannel");
    bool bVirtual             = pItem->GetPropertyBOOL("Virtual");
    bool bEPGEnabled          = pItem->GetPropertyBOOL("UseEPG");
    int iEPGSource            = pItem->GetPropertyInt("EPGSource");
    CStdString strChannelName = pItem->GetProperty("Name");
    CStdString strIconPath    = pItem->GetProperty("Icon");
    CStdString strStreamURL   = pItem->GetProperty("StreamURL");

    /* set new values in the channel tag */
// TODO
//    if (bHidden)
//      bChanged = channel->SetChannelNumber(iNextHiddenChannelNumber++) || bChanged;
//    else
//      bChanged = channel->SetChannelNumber(iNextChannelNumber++) || bChanged;
    bChanged = channel->SetChannelName(strChannelName) || bChanged;
    bChanged = channel->SetHidden(bHidden) || bChanged;
    bChanged = channel->SetIconPath(strIconPath) || bChanged;
    if (bVirtual)
      bChanged = channel->SetStreamURL(strStreamURL) || bChanged;

    if (iEPGSource == 0)
      bChanged = channel->SetEPGScraper("client") || bChanged;
    // TODO add other scrapers
    bChanged = channel->SetEPGEnabled(bEPGEnabled) || bChanged;

    if (bChanged)
    {
      bHasChangedItems = true;
      channel->Persist(true);
    }

    pItem->SetProperty("Changed", false);
    pDlgProgress->SetPercentage(iListPtr * 100 / m_channelItems->Size());
  }

  if (bHasChangedItems)
  {
    database->CommitInsertQueries();
    CPVRManager::Get()->Start(); // XXX not a nice way to refresh the channels, but works for now
  }

  database->Close();

  m_bContainsChanges = false;
  pDlgProgress->Close();
}