[coreSubs] set default services for Tv Shows and Movies
[vuplus_xbmc] / xbmc / video / dialogs / GUIDialogSubtitles.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://www.xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "system.h"
22 #include "GUIUserMessages.h"
23 #include "Application.h"
24 #include "GUIDialogSubtitles.h"
25 #include "addons/AddonManager.h"
26 #include "cores/IPlayer.h"
27 #include "dialogs/GUIDialogKaiToast.h"
28 #include "filesystem/AddonsDirectory.h"
29 #include "filesystem/File.h"
30 #include "filesystem/PluginDirectory.h"
31 #include "filesystem/SpecialProtocol.h"
32 #include "guilib/GUIImage.h"
33 #include "settings/MediaSettings.h"
34 #include "settings/Settings.h"
35 #include "settings/VideoSettings.h"
36 #include "settings/lib/Setting.h"
37 #include "utils/JobManager.h"
38 #include "utils/LangCodeExpander.h"
39 #include "utils/log.h"
40 #include "utils/StringUtils.h"
41 #include "utils/URIUtils.h"
42 #include "URL.h"
43 #include "Util.h"
44 #include "video/VideoDatabase.h"
45
46 using namespace ADDON;
47 using namespace XFILE;
48
49 #define CONTROL_NAMELABEL            100
50 #define CONTROL_NAMELOGO             110
51 #define CONTROL_SUBLIST              120
52 #define CONTROL_SUBSEXIST            130
53 #define CONTROL_SUBSTATUS            140
54 #define CONTROL_SERVICELIST          150
55
56 /*! \brief simple job to retrieve a directory and store a string (language)
57  */
58 class CSubtitlesJob: public CJob
59 {
60 public:
61   CSubtitlesJob(const CURL &url, const std::string &language) : m_url(url), m_language(language)
62   {
63     m_items = new CFileItemList;
64   }
65   virtual ~CSubtitlesJob()
66   {
67     delete m_items;
68   }
69   virtual bool DoWork()
70   {
71     CDirectory::GetDirectory(m_url.Get(), *m_items);
72     return true;
73   }
74   virtual bool operator==(const CJob *job) const
75   {
76     if (strcmp(job->GetType(),GetType()) == 0)
77     {
78       const CSubtitlesJob* rjob = dynamic_cast<const CSubtitlesJob*>(job);
79       if (rjob)
80       {
81         return m_url.Get() == rjob->m_url.Get() &&
82                m_language == rjob->m_language;
83       }
84     }
85     return false;
86   }
87   const CFileItemList *GetItems() const { return m_items; }
88   const CURL &GetURL() const { return m_url; }
89   const std::string &GetLanguage() const { return m_language; }
90 private:
91   CURL           m_url;
92   CFileItemList *m_items;
93   std::string    m_language;
94 };
95
96 CGUIDialogSubtitles::CGUIDialogSubtitles(void)
97     : CGUIDialog(WINDOW_DIALOG_SUBTITLES, "DialogSubtitles.xml")
98 {
99   m_loadType  = KEEP_IN_MEMORY;
100   m_subtitles = new CFileItemList;
101   m_serviceItems = new CFileItemList;
102   m_pausedOnRun = false;
103   m_updateSubsList = false;
104 }
105
106 CGUIDialogSubtitles::~CGUIDialogSubtitles(void)
107 {
108   CancelJobs();
109   delete m_subtitles;
110   delete m_serviceItems;
111 }
112
113 bool CGUIDialogSubtitles::OnMessage(CGUIMessage& message)
114 {
115   if  (message.GetMessage() == GUI_MSG_CLICKED)
116   {
117     int iControl = message.GetSenderId();
118
119     if (iControl == CONTROL_SUBLIST)
120     {
121       CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_SUBLIST);
122       OnMessage(msg);
123
124       int item = msg.GetParam1();
125       if (item >= 0 && item < m_subtitles->Size())
126         Download(*m_subtitles->Get(item));
127       return true;
128     }
129     else if (iControl == CONTROL_SERVICELIST)
130     {
131       CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_SERVICELIST);
132       OnMessage(msg);
133
134       int item = msg.GetParam1();
135       if (item >= 0 && item < m_serviceItems->Size() &&
136           SetService(m_serviceItems->Get(item)->GetProperty("Addon.ID").asString()))
137         Search();
138
139       return true;
140     }
141   }
142   else if (message.GetMessage() == GUI_MSG_WINDOW_DEINIT)
143   {
144     // Resume the video if the user has requested it
145     if (g_application.m_pPlayer->IsPaused() && m_pausedOnRun)
146       g_application.m_pPlayer->Pause();
147
148     CGUIDialog::OnMessage(message);
149
150     ClearSubtitles();
151     ClearServices();
152     return true;
153   }
154   return CGUIDialog::OnMessage(message);
155 }
156
157 void CGUIDialogSubtitles::OnInitWindow()
158 {
159   // Pause the video if the user has requested it
160   m_pausedOnRun = false;
161   if (CSettings::Get().GetBool("subtitles.pauseonsearch") && !g_application.m_pPlayer->IsPaused())
162   {
163     g_application.m_pPlayer->Pause();
164     m_pausedOnRun = true;
165   }
166
167   FillServices();
168   CGUIWindow::OnInitWindow();
169   Search();
170 }
171
172 void CGUIDialogSubtitles::Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
173 {
174   if (m_bInvalidated)
175   {
176     // take copies of our variables to ensure we don't hold the lock for long.
177     std::string status;
178     CFileItemList subs;
179     {
180       CSingleLock lock(m_section);
181       status = m_status;
182       subs.Assign(*m_subtitles);
183     }
184     SET_CONTROL_LABEL(CONTROL_SUBSTATUS, status);
185
186     if (m_updateSubsList)
187     {
188       CGUIMessage message(GUI_MSG_LABEL_BIND, GetID(), CONTROL_SUBLIST, 0, 0, &subs);
189       OnMessage(message);
190       m_updateSubsList = false;
191     }
192
193     if (!m_subtitles->IsEmpty() && !GetFocusedControl())
194     { // set focus to the list
195       CGUIMessage msg(GUI_MSG_SETFOCUS, GetID(), CONTROL_SUBLIST);
196       OnMessage(msg);
197     }
198   }
199   CGUIDialog::Process(currentTime, dirtyregions);
200 }
201
202 void CGUIDialogSubtitles::FillServices()
203 {
204   ClearServices();
205
206   VECADDONS addons;
207   ADDON::CAddonMgr::Get().GetAddons(ADDON_SUBTITLE_MODULE, addons, true);
208
209   if (addons.empty())
210   {
211     UpdateStatus(NO_SERVICES);
212     return;
213   }
214
215   std::string defaultService;
216   const CFileItem &item = g_application.CurrentFileItem();
217   if (item.GetVideoContentType() == VIDEODB_CONTENT_TVSHOWS ||
218       item.GetVideoContentType() == VIDEODB_CONTENT_EPISODES)
219     // Set default service for tv shows
220     defaultService = CSettings::Get().GetString("subtitles.tv");
221   else
222     // Set default service for filemode and movies
223     defaultService = CSettings::Get().GetString("subtitles.movie");
224   
225   std::string service = addons.front()->ID();
226   for (VECADDONS::const_iterator addonIt = addons.begin(); addonIt != addons.end(); addonIt++)
227   {
228     CFileItemPtr item(CAddonsDirectory::FileItemFromAddon(*addonIt, "plugin://", false));
229     m_serviceItems->Add(item);
230     if ((*addonIt)->ID() == defaultService)
231       service = (*addonIt)->ID();
232   }
233
234   // Bind our services to the UI
235   CGUIMessage msg(GUI_MSG_LABEL_BIND, GetID(), CONTROL_SERVICELIST, 0, 0, m_serviceItems);
236   OnMessage(msg);
237
238   SetService(service);
239 }
240
241 bool CGUIDialogSubtitles::SetService(const std::string &service)
242 {
243   if (service != m_currentService)
244   {
245     m_currentService = service;
246     CLog::Log(LOGDEBUG, "New Service [%s] ", m_currentService.c_str());
247
248     CFileItemPtr currentService = GetService();
249     // highlight this item in the skin
250     for (int i = 0; i < m_serviceItems->Size(); i++)
251     {
252       CFileItemPtr pItem = m_serviceItems->Get(i);
253       pItem->Select(pItem == currentService);
254     }
255
256     SET_CONTROL_LABEL(CONTROL_NAMELABEL, currentService->GetLabel());
257
258     CGUIImage* image = (CGUIImage*)GetControl(CONTROL_NAMELOGO);
259     if (image)
260     {
261       std::string icon = URIUtils::AddFileToFolder(currentService->GetProperty("Addon.Path").asString(), "logo.png");
262       image->SetFileName(icon);
263     }
264     if (g_application.m_pPlayer->GetSubtitleCount() == 0)
265       SET_CONTROL_HIDDEN(CONTROL_SUBSEXIST);
266     else
267       SET_CONTROL_VISIBLE(CONTROL_SUBSEXIST);
268
269     return true;
270   }
271   return false;
272 }
273
274 const CFileItemPtr CGUIDialogSubtitles::GetService() const
275 {
276   for (int i = 0; i < m_serviceItems->Size(); i++)
277   {
278     if (m_serviceItems->Get(i)->GetProperty("Addon.ID") == m_currentService)
279       return m_serviceItems->Get(i);
280   }
281   return CFileItemPtr();
282 }
283
284 void CGUIDialogSubtitles::Search()
285 {
286   if (m_currentService.empty())
287     return; // no services available
288
289   UpdateStatus(SEARCHING);
290   ClearSubtitles();
291
292   CURL url("plugin://" + m_currentService + "/");
293   url.SetOption("action", "search");
294
295   const CSetting *setting = CSettings::Get().GetSetting("subtitles.languages");
296   if (setting)
297     url.SetOption("languages", setting->ToString());
298
299   AddJob(new CSubtitlesJob(url, ""));
300 }
301
302 void CGUIDialogSubtitles::OnJobComplete(unsigned int jobID, bool success, CJob *job)
303 {
304   const CURL &url             = ((CSubtitlesJob *)job)->GetURL();
305   const CFileItemList *items  = ((CSubtitlesJob *)job)->GetItems();
306   const std::string &language = ((CSubtitlesJob *)job)->GetLanguage();
307   if (url.GetOption("action") == "search")
308     OnSearchComplete(items);
309   else
310     OnDownloadComplete(items, language);
311   CJobQueue::OnJobComplete(jobID, success, job);
312 }
313
314 void CGUIDialogSubtitles::OnSearchComplete(const CFileItemList *items)
315 {
316   CSingleLock lock(m_section);
317   m_subtitles->Assign(*items);
318   UpdateStatus(SEARCH_COMPLETE);
319   m_updateSubsList = true;
320   SetInvalid();
321 }
322
323 void CGUIDialogSubtitles::UpdateStatus(STATUS status)
324 {
325   CSingleLock lock(m_section);
326   std::string label;
327   switch (status)
328   {
329     case NO_SERVICES:
330       label = g_localizeStrings.Get(24114);
331       break;
332     case SEARCHING:
333       label = g_localizeStrings.Get(24107);
334       break;
335     case SEARCH_COMPLETE:
336       if (!m_subtitles->IsEmpty())
337         label = StringUtils::Format(g_localizeStrings.Get(24108).c_str(), m_subtitles->Size());
338       else
339         label = g_localizeStrings.Get(24109);
340       break;
341     case DOWNLOADING:
342       label = g_localizeStrings.Get(24110);
343       break;
344     default:
345       break;
346   }
347   if (label != m_status)
348   {
349     m_status = label;
350     SetInvalid();
351   }
352 }
353
354 void CGUIDialogSubtitles::Download(const CFileItem &subtitle)
355 {
356   UpdateStatus(DOWNLOADING);
357
358   // subtitle URL should be of the form plugin://<addonid>/?param=foo&param=bar
359   // we just append (if not already present) the action=download parameter.
360   CURL url(subtitle.GetAsUrl());
361   if (url.GetOption("action").empty())
362     url.SetOption("action", "download");
363
364   AddJob(new CSubtitlesJob(url, subtitle.GetLabel()));
365 }
366
367 void CGUIDialogSubtitles::OnDownloadComplete(const CFileItemList *items, const std::string &language)
368 {
369   if (items->IsEmpty())
370   {
371     CFileItemPtr service = GetService();
372     if (service)
373       CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, service->GetLabel(), g_localizeStrings.Get(24113));
374     UpdateStatus(SEARCH_COMPLETE);
375     return;
376   }
377
378   CStdString strFileName;
379   CStdString strDestPath;
380   if (g_application.CurrentFileItem().IsStack())
381   {
382     for (int i = 0; i < items->Size(); i++)
383     {
384 //    check for all stack items and match to given subs, item [0] == CD1, item [1] == CD2
385 //    CLog::Log(LOGDEBUG, "Stack Subs [%s} Found", vecItems[i]->GetLabel().c_str());
386     }
387   }
388   else if (StringUtils::StartsWith(g_application.CurrentFile(), "http://"))
389   {
390     strFileName = "TemporarySubs";
391     strDestPath = "special://temp/";
392   }
393   else
394   {
395     strFileName = URIUtils::GetFileName(g_application.CurrentFile());
396     if (CSettings::Get().GetBool("subtitles.savetomoviefolder"))
397     {
398       strDestPath = URIUtils::GetDirectory(g_application.CurrentFile());
399       if (!CUtil::SupportsWriteFileOperations(strDestPath))
400         strDestPath.clear();
401     }
402     if (strDestPath.empty())
403     {
404       if (CSpecialProtocol::TranslatePath("special://subtitles").empty())
405         strDestPath = "special://temp";
406       else
407         strDestPath = "special://subtitles";
408     }
409   }
410   // Extract the language and appropriate extension
411   CStdString strSubLang;
412   g_LangCodeExpander.ConvertToTwoCharCode(strSubLang, language);
413   CStdString strUrl = items->Get(0)->GetPath();
414   CStdString strSubExt = URIUtils::GetExtension(strUrl);
415
416   // construct subtitle path
417   URIUtils::RemoveExtension(strFileName);
418   CStdString strSubName = StringUtils::Format("%s.%s%s", strFileName.c_str(), strSubLang.c_str(), strSubExt.c_str());
419   CStdString strSubPath = URIUtils::AddFileToFolder(strDestPath, strSubName);
420
421   // and copy the file across
422   CFile::Cache(strUrl, strSubPath);
423   SetSubtitles(strSubPath);
424   // Close the window
425   Close();
426 }
427
428 void CGUIDialogSubtitles::ClearSubtitles()
429 {
430   CGUIMessage msg(GUI_MSG_LABEL_RESET, GetID(), CONTROL_SUBLIST);
431   OnMessage(msg);
432   CSingleLock lock(m_section);
433   m_subtitles->Clear();
434 }
435
436 void CGUIDialogSubtitles::ClearServices()
437 {
438   CGUIMessage msg(GUI_MSG_LABEL_RESET, GetID(), CONTROL_SERVICELIST);
439   OnMessage(msg);
440   m_serviceItems->Clear();
441   m_currentService.clear();
442 }
443
444 void CGUIDialogSubtitles::SetSubtitles(const std::string &subtitle)
445 {
446   if (g_application.m_pPlayer)
447   {
448     int nStream = g_application.m_pPlayer->AddSubtitle(subtitle);
449     if(nStream >= 0)
450     {
451       g_application.m_pPlayer->SetSubtitle(nStream);
452       g_application.m_pPlayer->SetSubtitleVisible(true);
453       CMediaSettings::Get().GetCurrentVideoSettings().m_SubtitleDelay = 0.0f;
454       g_application.m_pPlayer->SetSubTitleDelay(0);
455     }
456   }
457 }