Debian Codegraph @

xbmc/windows/GUIMediaWindow.cpp

raw
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "GUIMediaWindow.h"
10
11 #include "ContextMenuManager.h"
12 #include "FileItem.h"
13 #include "FileItemListModification.h"
14 #include "GUIPassword.h"
15 #include "GUIUserMessages.h"
16 #include "PartyModeManager.h"
17 #include "PlayListPlayer.h"
18 #include "ServiceBroker.h"
19 #include "URL.h"
20 #include "Util.h"
21 #include "addons/AddonManager.h"
22 #include "addons/PluginSource.h"
23 #include "addons/addoninfo/AddonType.h"
24 #include "application/Application.h"
25 #include "messaging/ApplicationMessenger.h"
26 #if defined(TARGET_ANDROID)
27 #include "platform/android/activity/XBMCApp.h"
28 #endif
29 #include "dialogs/GUIDialogBusy.h"
30 #include "dialogs/GUIDialogKaiToast.h"
31 #include "dialogs/GUIDialogMediaFilter.h"
32 #include "dialogs/GUIDialogProgress.h"
33 #include "dialogs/GUIDialogSmartPlaylistEditor.h"
34 #include "filesystem/FileDirectoryFactory.h"
35 #include "filesystem/MultiPathDirectory.h"
36 #include "filesystem/PluginDirectory.h"
37 #include "filesystem/SmartPlaylistDirectory.h"
38 #include "guilib/GUIComponent.h"
39 #include "guilib/GUIEditControl.h"
40 #include "guilib/GUIKeyboardFactory.h"
41 #include "guilib/GUIWindowManager.h"
42 #include "guilib/LocalizeStrings.h"
43 #include "input/actions/Action.h"
44 #include "input/actions/ActionIDs.h"
45 #include "interfaces/generic/ScriptInvocationManager.h"
46 #include "messaging/helpers/DialogOKHelper.h"
47 #include "network/Network.h"
48 #include "playlists/PlayList.h"
49 #include "profiles/ProfileManager.h"
50 #include "settings/AdvancedSettings.h"
51 #include "settings/Settings.h"
52 #include "settings/SettingsComponent.h"
53 #include "storage/MediaManager.h"
54 #include "threads/IRunnable.h"
55 #include "utils/FileUtils.h"
56 #include "utils/LabelFormatter.h"
57 #include "utils/SortUtils.h"
58 #include "utils/StringUtils.h"
59 #include "utils/URIUtils.h"
60 #include "utils/Variant.h"
61 #include "utils/log.h"
62 #include "view/GUIViewState.h"
63
64 #include <inttypes.h>
65
66 #define CONTROL_BTNVIEWASICONS 2
67 #define CONTROL_BTNSORTBY 3
68 #define CONTROL_BTNSORTASC 4
69 #define CONTROL_BTN_FILTER 19
70
71 #define CONTROL_LABELFILES 12
72
73 #define PROPERTY_PATH_DB "path.db"
74 #define PROPERTY_SORT_ORDER "sort.order"
75 #define PROPERTY_SORT_ASCENDING "sort.ascending"
76
77 #define PLUGIN_REFRESH_DELAY 200
78
79 using namespace ADDON;
80 using namespace KODI::MESSAGING;
81 using namespace std::chrono_literals;
82
83 namespace
84 {
85 class CGetDirectoryItems : public IRunnable
86 {
87 public:
88 CGetDirectoryItems(XFILE::CVirtualDirectory &dir, CURL &url, CFileItemList &items, bool useDir)
89 : m_dir(dir), m_url(url), m_items(items), m_useDir(useDir)
90 {
91 }
92
93 void Run() override
94 {
95 m_result = m_dir.GetDirectory(m_url, m_items, m_useDir, true);
96 }
97
98 void Cancel() override
99 {
100 m_dir.CancelDirectory();
101 }
102
103 bool m_result = false;
104
105 protected:
106 XFILE::CVirtualDirectory &m_dir;
107 CURL m_url;
108 CFileItemList &m_items;
109 bool m_useDir;
110 };
111 }
112
113 CGUIMediaWindow::CGUIMediaWindow(int id, const char *xmlFile)
114 : CGUIWindow(id, xmlFile)
115 {
116 m_loadType = KEEP_IN_MEMORY;
117 m_vecItems = new CFileItemList;
118 m_unfilteredItems = new CFileItemList;
119 m_vecItems->SetPath("?");
120 m_iLastControl = -1;
121 m_canFilterAdvanced = false;
122
123 m_guiState.reset(CGUIViewState::GetViewState(GetID(), *m_vecItems));
124 }
125
126 CGUIMediaWindow::~CGUIMediaWindow()
127 {
128 delete m_vecItems;
129 delete m_unfilteredItems;
130 }
131
132 bool CGUIMediaWindow::Load(TiXmlElement *pRootElement)
133 {
134 bool retVal = CGUIWindow::Load(pRootElement);
135
136 if (!retVal)
137 return false;
138
139 // configure our view control
140 m_viewControl.Reset();
141 m_viewControl.SetParentWindow(GetID());
142 TiXmlElement *element = pRootElement->FirstChildElement("views");
143 if (element && element->FirstChild())
144 { // format is <views>50,29,51,95</views>
145 const std::string &allViews = element->FirstChild()->ValueStr();
146 std::vector<std::string> views = StringUtils::Split(allViews, ",");
147 for (std::vector<std::string>::const_iterator i = views.begin(); i != views.end(); ++i)
148 {
149 int controlID = atol(i->c_str());
150 CGUIControl *control = GetControl(controlID);
151 if (control && control->IsContainer())
152 m_viewControl.AddView(control);
153 }
154 }
155 m_viewControl.SetViewControlID(CONTROL_BTNVIEWASICONS);
156
157 return true;
158 }
159
160 void CGUIMediaWindow::OnWindowLoaded()
161 {
162 SendMessage(GUI_MSG_SET_TYPE, CONTROL_BTN_FILTER, CGUIEditControl::INPUT_TYPE_FILTER);
163 CGUIWindow::OnWindowLoaded();
164 SetupShares();
165 }
166
167 void CGUIMediaWindow::OnWindowUnload()
168 {
169 CGUIWindow::OnWindowUnload();
170 m_viewControl.Reset();
171 }
172
173 CFileItemPtr CGUIMediaWindow::GetCurrentListItem(int offset)
174 {
175 int item = m_viewControl.GetSelectedItem();
176 if (!m_vecItems->Size() || item < 0)
177 return CFileItemPtr();
178 item = (item + offset) % m_vecItems->Size();
179 if (item < 0) item += m_vecItems->Size();
180 return m_vecItems->Get(item);
181 }
182
183 bool CGUIMediaWindow::OnAction(const CAction &action)
184 {
185 if (action.GetID() == ACTION_PARENT_DIR)
186 {
187 GoParentFolder();
188 return true;
189 }
190
191 if (CGUIWindow::OnAction(action))
192 return true;
193
194 if (action.GetID() == ACTION_FILTER)
195 return Filter();
196
197 // live filtering
198 if (action.GetID() == ACTION_FILTER_CLEAR)
199 {
200 CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, GUI_MSG_FILTER_ITEMS);
201 message.SetStringParam("");
202 OnMessage(message);
203 return true;
204 }
205
206 if (action.GetID() == ACTION_BACKSPACE)
207 {
208 CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, GUI_MSG_FILTER_ITEMS, 2); // 2 for delete
209 OnMessage(message);
210 return true;
211 }
212
213 if (action.GetID() >= ACTION_FILTER_SMS2 && action.GetID() <= ACTION_FILTER_SMS9)
214 {
215 std::string filter = std::to_string(action.GetID() - ACTION_FILTER_SMS2 + 2);
216 CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, GUI_MSG_FILTER_ITEMS, 1); // 1 for append
217 message.SetStringParam(filter);
218 OnMessage(message);
219 return true;
220 }
221
222 return false;
223 }
224
225 bool CGUIMediaWindow::OnBack(int actionID)
226 {
227 CURL filterUrl(m_strFilterPath);
228 if (actionID == ACTION_NAV_BACK &&
229 !m_vecItems->IsVirtualDirectoryRoot() &&
230 !URIUtils::PathEquals(m_vecItems->GetPath(), GetRootPath(), true) &&
231 (!URIUtils::PathEquals(m_vecItems->GetPath(), m_startDirectory, true) || (m_canFilterAdvanced && filterUrl.HasOption("filter"))))
232 {
233 if (GoParentFolder())
234 return true;
235 }
236 return CGUIWindow::OnBack(actionID);
237 }
238
239 bool CGUIMediaWindow::OnMessage(CGUIMessage& message)
240 {
241 switch ( message.GetMessage() )
242 {
243 case GUI_MSG_WINDOW_DEINIT:
244 {
245 m_iLastControl = GetFocusedControlID();
246 CGUIWindow::OnMessage(message);
247
248 // get rid of any active filtering
249 if (m_canFilterAdvanced)
250 {
251 m_canFilterAdvanced = false;
252 m_filter.Reset();
253 }
254 m_strFilterPath.clear();
255
256 // Call ClearFileItems() after our window has finished doing any WindowClose
257 // animations
258 ClearFileItems();
259 return true;
260 }
261 break;
262
263 case GUI_MSG_CLICKED:
264 {
265 int iControl = message.GetSenderId();
266 if (iControl == CONTROL_BTNVIEWASICONS)
267 {
268 // view as control could be a select button
269 int viewMode = 0;
270 const CGUIControl *control = GetControl(CONTROL_BTNVIEWASICONS);
271 if (control && control->GetControlType() != CGUIControl::GUICONTROL_BUTTON)
272 {
273 CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_BTNVIEWASICONS);
274 OnMessage(msg);
275 viewMode = m_viewControl.GetViewModeNumber(msg.GetParam1());
276 }
277 else
278 viewMode = m_viewControl.GetNextViewMode();
279
280 if (m_guiState)
281 m_guiState->SaveViewAsControl(viewMode);
282
283 UpdateButtons();
284 return true;
285 }
286 else if (iControl == CONTROL_BTNSORTASC) // sort asc
287 {
288 if (m_guiState)
289 m_guiState->SetNextSortOrder();
290 UpdateFileList();
291 return true;
292 }
293 else if (iControl == CONTROL_BTNSORTBY) // sort by
294 {
295 if (m_guiState.get() && m_guiState->ChooseSortMethod())
296 UpdateFileList();
297 return true;
298 }
299 else if (iControl == CONTROL_BTN_FILTER)
300 return Filter(false);
301 else if (m_viewControl.HasControl(iControl)) // list/thumb control
302 {
303 int iItem = m_viewControl.GetSelectedItem();
304 int iAction = message.GetParam1();
305 if (iItem < 0) break;
306 if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK)
307 {
308 OnSelect(iItem);
309 }
310 else if (iAction == ACTION_CONTEXT_MENU || iAction == ACTION_MOUSE_RIGHT_CLICK)
311 {
312 OnPopupMenu(iItem);
313 return true;
314 }
315 }
316 }
317 break;
318
319 case GUI_MSG_SETFOCUS:
320 {
321 if (m_viewControl.HasControl(message.GetControlId()) && m_viewControl.GetCurrentControl() != message.GetControlId())
322 {
323 m_viewControl.SetFocused();
324 return true;
325 }
326 }
327 break;
328
329 case GUI_MSG_NOTIFY_ALL:
330 { // Message is received even if this window is inactive
331 if (message.GetParam1() == GUI_MSG_WINDOW_RESET)
332 {
333 m_vecItems->SetPath("?");
334 return true;
335 }
336 else if ( message.GetParam1() == GUI_MSG_REFRESH_THUMBS )
337 {
338 for (int i = 0; i < m_vecItems->Size(); i++)
339 m_vecItems->Get(i)->FreeMemory(true);
340 break; // the window will take care of any info images
341 }
342 else if (message.GetParam1() == GUI_MSG_REMOVED_MEDIA)
343 {
344 if ((m_vecItems->IsVirtualDirectoryRoot() ||
345 m_vecItems->IsSourcesPath()) && IsActive())
346 {
347 int iItem = m_viewControl.GetSelectedItem();
348 Refresh();
349 m_viewControl.SetSelectedItem(iItem);
350 }
351 else if (m_vecItems->IsRemovable())
352 { // check that we have this removable share still
353 if (!m_rootDir.IsInSource(m_vecItems->GetPath()))
354 { // don't have this share any more
355 if (IsActive()) Update("");
356 else
357 {
358 m_history.ClearPathHistory();
359 m_vecItems->SetPath("");
360 }
361 }
362 }
363
364 return true;
365 }
366 else if (message.GetParam1()==GUI_MSG_UPDATE_SOURCES)
367 { // State of the sources changed, so update our view
368 if ((m_vecItems->IsVirtualDirectoryRoot() ||
369 m_vecItems->IsSourcesPath()) && IsActive())
370 {
371 if (m_vecItemsUpdating)
372 {
373 CLog::Log(LOGWARNING, "CGUIMediaWindow::OnMessage - updating in progress");
374 return true;
375 }
376 CUpdateGuard ug(m_vecItemsUpdating);
377 int iItem = m_viewControl.GetSelectedItem();
378 Refresh(true);
379 m_viewControl.SetSelectedItem(iItem);
380 }
381 return true;
382 }
383 else if (message.GetParam1()==GUI_MSG_UPDATE && IsActive())
384 {
385 if (m_vecItemsUpdating)
386 {
387 CLog::Log(LOGWARNING, "CGUIMediaWindow::OnMessage - updating in progress");
388 return true;
389 }
390 CUpdateGuard ug(m_vecItemsUpdating);
391 if (message.GetNumStringParams())
392 {
393 if (message.GetParam2()) // param2 is used for resetting the history
394 SetHistoryForPath(message.GetStringParam());
395
396 CFileItemList list(message.GetStringParam());
397 list.RemoveDiscCache(GetID());
398 Update(message.GetStringParam());
399 }
400 else
401 Refresh(true); // refresh the listing
402 }
403 else if (message.GetParam1()==GUI_MSG_UPDATE_ITEM && message.GetItem())
404 {
405 int flag = message.GetParam2();
406 CFileItemPtr newItem = std::static_pointer_cast<CFileItem>(message.GetItem());
407
408 if (IsActive() || (flag & GUI_MSG_FLAG_FORCE_UPDATE))
409 {
410 m_vecItems->UpdateItem(newItem.get());
411
412 if (flag & GUI_MSG_FLAG_UPDATE_LIST)
413 { // need the list updated as well
414 UpdateFileList();
415 }
416 }
417 else if (newItem)
418 { // need to remove the disc cache
419 CFileItemList items;
420 items.SetPath(URIUtils::GetDirectory(newItem->GetPath()));
421 if (newItem->HasProperty("cachefilename"))
422 {
423 // Use stored cache file name
424 std::string crcfile = newItem->GetProperty("cachefilename").asString();
425 items.RemoveDiscCacheCRC(crcfile);
426 }
427 else
428 // No stored cache file name, attempt using truncated item path as list path
429 items.RemoveDiscCache(GetID());
430 }
431 }
432 else if (message.GetParam1()==GUI_MSG_UPDATE_PATH)
433 {
434 if (IsActive())
435 {
436 if((message.GetStringParam() == m_vecItems->GetPath()) ||
437 (m_vecItems->IsMultiPath() && XFILE::CMultiPathDirectory::HasPath(m_vecItems->GetPath(), message.GetStringParam())))
438 Refresh();
439 }
440 }
441 else if (message.GetParam1() == GUI_MSG_FILTER_ITEMS && IsActive())
442 {
443 std::string filter = GetProperty("filter").asString();
444 // check if this is meant for advanced filtering
445 if (message.GetParam2() != 10)
446 {
447 if (message.GetParam2() == 1) // append
448 filter += message.GetStringParam();
449 else if (message.GetParam2() == 2)
450 { // delete
451 if (filter.size())
452 filter.erase(filter.size() - 1);
453 }
454 else
455 filter = message.GetStringParam();
456 }
457 OnFilterItems(filter);
458 UpdateButtons();
459 return true;
460 }
461 else
462 return CGUIWindow::OnMessage(message);
463
464 return true;
465 }
466 break;
467 case GUI_MSG_PLAYBACK_STARTED:
468 case GUI_MSG_PLAYBACK_ENDED:
469 case GUI_MSG_PLAYBACK_STOPPED:
470 case GUI_MSG_PLAYLIST_CHANGED:
471 case GUI_MSG_PLAYLISTPLAYER_STOPPED:
472 case GUI_MSG_PLAYLISTPLAYER_STARTED:
473 case GUI_MSG_PLAYLISTPLAYER_CHANGED:
474 { // send a notify all to all controls on this window
475 CGUIMessage msg(GUI_MSG_NOTIFY_ALL, GetID(), 0, GUI_MSG_REFRESH_LIST);
476 OnMessage(msg);
477 break;
478 }
479 case GUI_MSG_CHANGE_VIEW_MODE:
480 {
481 int viewMode = 0;
482 if (message.GetParam1()) // we have an id
483 viewMode = m_viewControl.GetViewModeByID(message.GetParam1());
484 else if (message.GetParam2())
485 viewMode = m_viewControl.GetNextViewMode(message.GetParam2());
486
487 if (m_guiState)
488 m_guiState->SaveViewAsControl(viewMode);
489 UpdateButtons();
490 return true;
491 }
492 break;
493 case GUI_MSG_CHANGE_SORT_METHOD:
494 {
495 if (m_guiState)
496 {
497 if (message.GetParam1())
498 m_guiState->SetCurrentSortMethod(message.GetParam1());
499 else if (message.GetParam2())
500 m_guiState->SetNextSortMethod(message.GetParam2());
501 }
502 UpdateFileList();
503 return true;
504 }
505 break;
506 case GUI_MSG_CHANGE_SORT_DIRECTION:
507 {
508 if (m_guiState)
509 m_guiState->SetNextSortOrder();
510 UpdateFileList();
511 return true;
512 }
513 break;
514 case GUI_MSG_WINDOW_INIT:
515 {
516 if (m_vecItems->GetPath() == "?")
517 m_vecItems->SetPath("");
518
519 std::string dir = message.GetStringParam(0);
520 const std::string& ret = message.GetStringParam(1);
521 const std::string& swap = message.GetStringParam(message.GetNumStringParams() - 1);
522 const bool returning = StringUtils::EqualsNoCase(ret, "return");
523 const bool replacing = StringUtils::EqualsNoCase(swap, "replace");
524
525 if (!dir.empty())
526 {
527 // ensure our directory is valid
528 dir = GetStartFolder(dir);
529 bool resetHistory = false;
530 if (!returning || !URIUtils::PathEquals(dir, m_startDirectory, true))
531 { // we're not returning to the same path, so set our directory to the requested path
532 m_vecItems->SetPath(dir);
533 resetHistory = true;
534 }
535 else if (m_vecItems->GetPath().empty() && URIUtils::PathEquals(dir, m_startDirectory, true))
536 m_vecItems->SetPath(dir);
537
538 // check for network up
539 if (URIUtils::IsRemote(m_vecItems->GetPath()) && !WaitForNetwork())
540 {
541 m_vecItems->SetPath("");
542 resetHistory = true;
543 }
544 if (resetHistory)
545 {
546 m_vecItems->RemoveDiscCache(GetID());
547 // only compute the history for the provided path if "return" is not defined
548 // (otherwise the root level for the path will be added by default to the path history
549 // and we won't be able to move back to the path we came from)
550 if (!returning)
551 SetHistoryForPath(m_vecItems->GetPath());
552 }
553 }
554 if (message.GetParam1() != WINDOW_INVALID)
555 {
556 // if this is the first time to this window - make sure we set the root path
557 // if "return" is defined make sure we set the startDirectory to the directory we are
558 // moving to (so that we can move back to where we were onBack). If we are activating
559 // the same window but with a different path, do nothing - we are simply adding to the
560 // window history. Note that if the window is just being replaced, the start directory
561 // also needs to be set as the manager has just popped the previous window.
562 if (message.GetParam1() != message.GetParam2() || replacing)
563 m_startDirectory = returning ? dir : GetRootPath();
564 }
565 if (message.GetParam2() == PLUGIN_REFRESH_DELAY)
566 {
567 Refresh();
568 SetInitialVisibility();
569 RestoreControlStates();
570 SetInitialVisibility();
571 return true;
572 }
573 }
574 break;
575 }
576
577 return CGUIWindow::OnMessage(message);
578 }
579
580 /*!
581 * \brief Updates the states
582 *
583 * This updates the states (enable, disable, visible...) of the controls defined
584 * by this window.
585 *
586 * \note Override this function in a derived class to add new controls
587 */
588 void CGUIMediaWindow::UpdateButtons()
589 {
590 if (m_guiState)
591 {
592 // Update sorting controls
593 if (m_guiState->GetSortOrder() == SortOrderNone)
594 {
595 CONTROL_DISABLE(CONTROL_BTNSORTASC);
596 }
597 else
598 {
599 CONTROL_ENABLE(CONTROL_BTNSORTASC);
600 SET_CONTROL_SELECTED(GetID(), CONTROL_BTNSORTASC, m_guiState->GetSortOrder() != SortOrderAscending);
601 }
602
603 // Update list/thumb control
604 m_viewControl.SetCurrentView(m_guiState->GetViewAsControl());
605
606 // Update sort by button
607 if (!m_guiState->HasMultipleSortMethods())
608 CONTROL_DISABLE(CONTROL_BTNSORTBY);
609 else
610 CONTROL_ENABLE(CONTROL_BTNSORTBY);
611
612 std::string sortLabel = StringUtils::Format(
613 g_localizeStrings.Get(550), g_localizeStrings.Get(m_guiState->GetSortMethodLabel()));
614 SET_CONTROL_LABEL(CONTROL_BTNSORTBY, sortLabel);
615 }
616
617 std::string items =
618 StringUtils::Format("{} {}", m_vecItems->GetObjectCount(), g_localizeStrings.Get(127));
619 SET_CONTROL_LABEL(CONTROL_LABELFILES, items);
620
621 SET_CONTROL_LABEL2(CONTROL_BTN_FILTER, GetProperty("filter").asString());
622 }
623
624 void CGUIMediaWindow::ClearFileItems()
625 {
626 m_viewControl.Clear();
627 m_vecItems->Clear();
628 m_unfilteredItems->Clear();
629 }
630
631 /*!
632 * \brief Sort file items
633 *
634 * This sorts file items based on the sort method and sort order provided by
635 * guiViewState.
636 */
637 void CGUIMediaWindow::SortItems(CFileItemList &items)
638 {
639 std::unique_ptr<CGUIViewState> guiState(CGUIViewState::GetViewState(GetID(), items));
640
641 if (guiState)
642 {
643 SortDescription sorting = guiState->GetSortMethod();
644 sorting.sortOrder = guiState->GetSortOrder();
645 // If the sort method is "sort by playlist" and we have a specific
646 // sort order available we can use the specified sort order to do the sorting
647 // We do this as the new SortBy methods are a superset of the SORT_METHOD methods, thus
648 // not all are available. This may be removed once SORT_METHOD_* have been replaced by
649 // SortBy.
650 if ((sorting.sortBy == SortByPlaylistOrder) && items.HasProperty(PROPERTY_SORT_ORDER))
651 {
652 SortBy sortBy = (SortBy)items.GetProperty(PROPERTY_SORT_ORDER).asInteger();
653 if (sortBy != SortByNone && sortBy != SortByPlaylistOrder && sortBy != SortByProgramCount)
654 {
655 sorting.sortBy = sortBy;
656 sorting.sortOrder = items.GetProperty(PROPERTY_SORT_ASCENDING).asBoolean() ? SortOrderAscending : SortOrderDescending;
657 sorting.sortAttributes = CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING) ? SortAttributeIgnoreArticle : SortAttributeNone;
658
659 // if the sort order is descending, we need to switch the original sort order, as we assume
660 // in CGUIViewState::AddPlaylistOrder that SortByPlaylistOrder is ascending.
661 if (guiState->GetSortOrder() == SortOrderDescending)
662 sorting.sortOrder = sorting.sortOrder == SortOrderDescending ? SortOrderAscending : SortOrderDescending;
663 }
664 }
665
666 items.Sort(sorting);
667 }
668 }
669
670 /*!
671 * \brief Formats item labels
672 *
673 * This is based on the formatting provided by guiViewState.
674 */
675 void CGUIMediaWindow::FormatItemLabels(CFileItemList &items, const LABEL_MASKS &labelMasks)
676 {
677 CLabelFormatter fileFormatter(labelMasks.m_strLabelFile, labelMasks.m_strLabel2File);
678 CLabelFormatter folderFormatter(labelMasks.m_strLabelFolder, labelMasks.m_strLabel2Folder);
679 for (int i=0; i<items.Size(); ++i)
680 {
681 CFileItemPtr pItem=items[i];
682
683 if (pItem->IsLabelPreformatted())
684 continue;
685
686 if (pItem->m_bIsFolder)
687 folderFormatter.FormatLabels(pItem.get());
688 else
689 fileFormatter.FormatLabels(pItem.get());
690 }
691
692 if (items.GetSortMethod() == SortByLabel)
693 items.ClearSortState();
694 }
695
696 /*!
697 * \brief Format and sort file items
698 *
699 * Prepares and adds the fileitems to list/thumb panel
700 */
701 void CGUIMediaWindow::FormatAndSort(CFileItemList &items)
702 {
703 std::unique_ptr<CGUIViewState> viewState(CGUIViewState::GetViewState(GetID(), items));
704
705 if (viewState)
706 {
707 LABEL_MASKS labelMasks;
708 viewState->GetSortMethodLabelMasks(labelMasks);
709 FormatItemLabels(items, labelMasks);
710
711 items.Sort(viewState->GetSortMethod().sortBy, viewState->GetSortOrder(), viewState->GetSortMethod().sortAttributes);
712 }
713 }
714
715 /*!
716 * \brief Overwrite to fill fileitems from a source
717 *
718 * \param[in] strDirectory Path to read
719 * \param[out] items Fill with items specified in \e strDirectory
720 * \return false if given directory not present
721 */
722 bool CGUIMediaWindow::GetDirectory(const std::string &strDirectory, CFileItemList &items)
723 {
724 CURL pathToUrl(strDirectory);
725
726 std::string strParentPath = m_history.GetParentPath();
727
728 CLog::Log(LOGDEBUG, "CGUIMediaWindow::GetDirectory ({})", CURL::GetRedacted(strDirectory));
729 CLog::Log(LOGDEBUG, " ParentPath = [{}]", CURL::GetRedacted(strParentPath));
730
731 if (pathToUrl.IsProtocol("plugin") && !pathToUrl.GetHostName().empty())
732 CServiceBroker::GetAddonMgr().UpdateLastUsed(pathToUrl.GetHostName());
733
734 // see if we can load a previously cached folder
735 CFileItemList cachedItems(strDirectory);
736 if (!strDirectory.empty() && cachedItems.Load(GetID()))
737 {
738 items.Assign(cachedItems);
739 }
740 else
741 {
742 auto start = std::chrono::steady_clock::now();
743
744 if (strDirectory.empty())
745 SetupShares();
746
747 CFileItemList dirItems;
748 if (!GetDirectoryItems(pathToUrl, dirItems, UseFileDirectories()))
749 return false;
750
751 // assign fetched directory items
752 items.Assign(dirItems);
753
754 // took over a second, and not normally cached, so cache it
755 auto end = std::chrono::steady_clock::now();
756 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
757
758 if (duration.count() > 1000 && items.CacheToDiscIfSlow())
759 items.Save(GetID());
760
761 // if these items should replace the current listing, then pop it off the top
762 if (items.GetReplaceListing())
763 m_history.RemoveParentPath();
764 }
765
766 // Store parent path along with item as parent path cannot safely be calculated from item's path.
767 for (const auto& item : items)
768 {
769 item->SetProperty("ParentPath", m_vecItems->GetPath());
770 }
771
772 // update the view state's reference to the current items
773 m_guiState.reset(CGUIViewState::GetViewState(GetID(), items));
774
775 bool bHideParent = false;
776
777 if (m_guiState && m_guiState->HideParentDirItems())
778 bHideParent = true;
779 if (items.GetPath() == GetRootPath())
780 bHideParent = true;
781
782 if (!bHideParent)
783 {
784 CFileItemPtr pItem(new CFileItem(".."));
785 pItem->SetPath(strParentPath);
786 pItem->m_bIsFolder = true;
787 pItem->m_bIsShareOrDrive = false;
788 items.AddFront(pItem, 0);
789 }
790
791 int iWindow = GetID();
792 std::vector<std::string> regexps;
793
794 //! @todo Do we want to limit the directories we apply the video ones to?
795 if (iWindow == WINDOW_VIDEO_NAV)
796 regexps = CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_videoExcludeFromListingRegExps;
797 if (iWindow == WINDOW_MUSIC_NAV)
798 regexps = CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_audioExcludeFromListingRegExps;
799 if (iWindow == WINDOW_PICTURES)
800 regexps = CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_pictureExcludeFromListingRegExps;
801
802 if (regexps.size())
803 {
804 for (int i=0; i < items.Size();)
805 {
806 if (CUtil::ExcludeFileOrFolder(items[i]->GetPath(), regexps))
807 items.Remove(i);
808 else
809 i++;
810 }
811 }
812
813 // clear the filter
814 SetProperty("filter", "");
815 m_canFilterAdvanced = false;
816 m_filter.Reset();
817 return true;
818 }
819
820 bool CGUIMediaWindow::Update(const std::string &strDirectory, bool updateFilterPath /* = true */)
821 {
822 //! @todo OnInitWindow calls Update() before window path has been set properly.
823 if (strDirectory == "?")
824 return false;
825
826 // The path to load. Empty string is used in various places to denote root, so translate to the
827 // real root path first
828 const std::string path = strDirectory.empty() ? GetRootPath() : strDirectory;
829
830 // stores the selected item in history
831 SaveSelectedItemInHistory();
832
833 const std::string previousPath = m_vecItems->GetPath();
834
835 // check if the path contains a filter and temporarily remove it
836 // so that the retrieved list of items is unfiltered
837 std::string pathNoFilter = path;
838 if (CanContainFilter(pathNoFilter) && CURL(pathNoFilter).HasOption("filter"))
839 pathNoFilter = RemoveParameterFromPath(pathNoFilter, "filter");
840
841 if (!GetDirectory(pathNoFilter, *m_vecItems))
842 {
843 CLog::Log(LOGERROR, "CGUIMediaWindow::GetDirectory({}) failed", CURL(path).GetRedacted());
844
845 if (URIUtils::PathEquals(path, GetRootPath()))
846 return false; // Nothing to fallback to
847
848 // Try to return to the previous directory, if not the same
849 // else fallback to root
850 if (URIUtils::PathEquals(path, previousPath) || !Update(m_history.RemoveParentPath()))
851 Update(""); // Fallback to root
852
853 // Return false to be able to eg. show
854 // an error message.
855 return false;
856 }
857
858 if (m_vecItems->GetLabel().empty())
859 {
860 // Removable sources
861 VECSOURCES removables;
862 CServiceBroker::GetMediaManager().GetRemovableDrives(removables);
863 for (const auto& s : removables)
864 {
865 if (URIUtils::CompareWithoutSlashAtEnd(s.strPath, m_vecItems->GetPath()))
866 {
867 m_vecItems->SetLabel(s.strName);
868 break;
869 }
870 }
871 }
872
873 if (m_vecItems->GetLabel().empty())
874 m_vecItems->SetLabel(CUtil::GetTitleFromPath(m_vecItems->GetPath(), true));
875
876 // check the given path for filter data
877 UpdateFilterPath(path, *m_vecItems, updateFilterPath);
878
879 // if we're getting the root source listing
880 // make sure the path history is clean
881 if (URIUtils::PathEquals(path, GetRootPath()))
882 m_history.ClearPathHistory();
883
884 int iWindow = GetID();
885 int showLabel = 0;
886 if (URIUtils::PathEquals(path, GetRootPath()))
887 {
888 if (iWindow == WINDOW_PICTURES)
889 showLabel = 997;
890 else if (iWindow == WINDOW_FILES)
891 showLabel = 1026;
892 else if (iWindow == WINDOW_GAMES)
893 showLabel = 35250; // "Add games..."
894 }
895 if (m_vecItems->IsPath("sources://video/"))
896 showLabel = 999;
897 else if (m_vecItems->IsPath("sources://music/"))
898 showLabel = 998;
899 else if (m_vecItems->IsPath("sources://pictures/"))
900 showLabel = 997;
901 else if (m_vecItems->IsPath("sources://files/"))
902 showLabel = 1026;
903 else if (m_vecItems->IsPath("sources://games/"))
904 showLabel = 35250; // "Add games..."
905 // Add 'Add source ' item
906 if (showLabel && (m_vecItems->Size() == 0 || !m_guiState->DisableAddSourceButtons()) &&
907 iWindow != WINDOW_MUSIC_PLAYLIST_EDITOR)
908 {
909 const std::string& strLabel = g_localizeStrings.Get(showLabel);
910 CFileItemPtr pItem(new CFileItem(strLabel));
911 pItem->SetPath("add");
912 pItem->SetArt("icon", "DefaultAddSource.png");
913 pItem->SetLabel(strLabel);
914 pItem->SetLabelPreformatted(true);
915 pItem->m_bIsFolder = true;
916 pItem->SetSpecialSort(CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_addSourceOnTop ?
917 SortSpecialOnTop : SortSpecialOnBottom);
918 m_vecItems->Add(pItem);
919 }
920 m_iLastControl = GetFocusedControlID();
921
922 // Check whether to enabled advanced filtering based on the content type
923 m_canFilterAdvanced = CheckFilterAdvanced(*m_vecItems);
924 if (m_canFilterAdvanced)
925 m_filter.SetType(m_vecItems->GetContent());
926
927 // Ask the derived class if it wants to load additional info
928 // for the fileitems like media info or additional
929 // filtering on the items, setting thumbs.
930 OnPrepareFileItems(*m_vecItems);
931
932 m_vecItems->FillInDefaultIcons();
933
934 // remember the original (untouched) list of items (for filtering etc)
935 m_unfilteredItems->Assign(*m_vecItems);
936
937 // Cache the list of items if possible
938 OnCacheFileItems(*m_vecItems);
939
940 // Filter and group the items if necessary
941 OnFilterItems(GetProperty("filter").asString());
942 UpdateButtons();
943
944 // Restore selected item from history
945 RestoreSelectedItemFromHistory();
946
947 m_history.AddPath(m_vecItems->GetPath(), m_strFilterPath);
948
949 //m_history.DumpPathHistory();
950
951 return true;
952 }
953
954 bool CGUIMediaWindow::Refresh(bool clearCache /* = false */)
955 {
956 std::string strCurrentDirectory = m_vecItems->GetPath();
957 if (strCurrentDirectory == "?")
958 return false;
959
960 if (clearCache)
961 m_vecItems->RemoveDiscCache(GetID());
962
963 bool ret = true;
964
965 // get the original number of items
966 if (!Update(strCurrentDirectory, false))
967 {
968 ret = false;
969 }
970
971 return ret;
972 }
973
974 /*!
975 * \brief On prepare file items
976 *
977 * This function will be called by Update() before the labels of the fileitems
978 * are formatted.
979 *
980 * \note Override this function to set custom thumbs or load additional media
981 * info.
982 *
983 * It's used to load tag info for music.
984 */
985 void CGUIMediaWindow::OnPrepareFileItems(CFileItemList &items)
986 {
987 CFileItemListModification::GetInstance().Modify(items);
988 }
989
990 /*!
991 * \brief On cache file items
992 *
993 * This function will be called by Update() before
994 * any additional formatting, filtering or sorting is applied.
995 *
996 * \note Override this function to define a custom caching behaviour.
997 */
998 void CGUIMediaWindow::OnCacheFileItems(CFileItemList &items)
999 {
1000 // Should these items be saved to the hdd
1001 if (items.CacheToDiscAlways() && !IsFiltered())
1002 items.Save(GetID());
1003 }
1004
1005 /*!
1006 * \brief On click
1007 *
1008 * With this function you can react on a users click in the list/thumb panel.
1009 * It returns true, if the click is handled.
1010 * This function calls OnPlayMedia()
1011 */
1012 bool CGUIMediaWindow::OnClick(int iItem, const std::string &player)
1013 {
1014 if (iItem < 0 || iItem >= m_vecItems->Size())
1015 return true;
1016
1017 const std::shared_ptr<CProfileManager> profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
1018
1019 CFileItemPtr pItem = m_vecItems->Get(iItem);
1020
1021 if (pItem->IsParentFolder())
1022 {
1023 GoParentFolder();
1024 return true;
1025 }
1026
1027 if (pItem->GetPath() == "add" || pItem->GetPath() == "sources://add/") // 'add source button' in empty root
1028 {
1029 if (profileManager->IsMasterProfile())
1030 {
1031 if (!g_passwordManager.IsMasterLockUnlocked(true))
1032 return false;
1033 }
1034 else if (!profileManager->GetCurrentProfile().canWriteSources() && !g_passwordManager.IsProfileLockUnlocked())
1035 return false;
1036
1037 if (OnAddMediaSource())
1038 Refresh(true);
1039
1040 return true;
1041 }
1042
1043 if (!pItem->m_bIsFolder && pItem->IsFileFolder(EFILEFOLDER_MASK_ONCLICK))
1044 {
1045 XFILE::IFileDirectory *pFileDirectory = nullptr;
1046 pFileDirectory = XFILE::CFileDirectoryFactory::Create(pItem->GetURL(), pItem.get(), "");
1047 if(pFileDirectory)
1048 pItem->m_bIsFolder = true;
1049 else if(pItem->m_bIsFolder)
1050 pItem->m_bIsFolder = false;
1051 delete pFileDirectory;
1052 }
1053
1054 if (pItem->IsScript())
1055 {
1056 // execute the script
1057 CURL url(pItem->GetPath());
1058 AddonPtr addon;
1059 if (CServiceBroker::GetAddonMgr().GetAddon(url.GetHostName(), addon, AddonType::SCRIPT,
1060 OnlyEnabled::CHOICE_YES))
1061 {
1062 if (!CScriptInvocationManager::GetInstance().Stop(addon->LibPath()))
1063 {
1064 CServiceBroker::GetAddonMgr().UpdateLastUsed(addon->ID());
1065 CScriptInvocationManager::GetInstance().ExecuteAsync(addon->LibPath(), addon);
1066 }
1067 return true;
1068 }
1069 }
1070
1071 if (pItem->m_bIsFolder)
1072 {
1073 if ( pItem->m_bIsShareOrDrive )
1074 {
1075 const std::string& strLockType=m_guiState->GetLockType();
1076 if (profileManager->GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE)
1077 if (!strLockType.empty() && !g_passwordManager.IsItemUnlocked(pItem.get(), strLockType))
1078 return true;
1079
1080 if (!HaveDiscOrConnection(pItem->GetPath(), pItem->m_iDriveType))
1081 return true;
1082 }
1083
1084 // check for the partymode playlist items - they may not exist yet
1085 if ((pItem->GetPath() == profileManager->GetUserDataItem("PartyMode.xsp")) ||
1086 (pItem->GetPath() == profileManager->GetUserDataItem("PartyMode-Video.xsp")))
1087 {
1088 // party mode playlist item - if it doesn't exist, prompt for user to define it
1089 if (!CFileUtils::Exists(pItem->GetPath()))
1090 {
1091 m_vecItems->RemoveDiscCache(GetID());
1092 if (CGUIDialogSmartPlaylistEditor::EditPlaylist(pItem->GetPath()))
1093 Refresh();
1094 return true;
1095 }
1096 }
1097
1098 // remove the directory cache if the folder is not normally cached
1099 CFileItemList items(pItem->GetPath());
1100 if (!items.AlwaysCache())
1101 items.RemoveDiscCache(GetID());
1102
1103 // if we have a filtered list, we need to add the filtered
1104 // path to be able to come back to the filtered view
1105 std::string strCurrentDirectory = m_vecItems->GetPath();
1106 if (m_canFilterAdvanced && !m_filter.IsEmpty() &&
1107 !URIUtils::PathEquals(m_strFilterPath, strCurrentDirectory))
1108 {
1109 m_history.RemoveParentPath();
1110 m_history.AddPath(strCurrentDirectory, m_strFilterPath);
1111 }
1112
1113 if (m_vecItemsUpdating)
1114 {
1115 CLog::Log(LOGWARNING, "CGUIMediaWindow::OnClick - updating in progress");
1116 return true;
1117 }
1118 CUpdateGuard ug(m_vecItemsUpdating);
1119
1120 CFileItem directory(*pItem);
1121 if (!Update(directory.GetPath()))
1122 ShowShareErrorMessage(&directory);
1123
1124 return true;
1125 }
1126 else if (pItem->IsPlugin() && !pItem->GetProperty("isplayable").asBoolean())
1127 {
1128 bool resume = pItem->GetStartOffset() == STARTOFFSET_RESUME;
1129 return XFILE::CPluginDirectory::RunScriptWithParams(pItem->GetPath(), resume);
1130 }
1131 #if defined(TARGET_ANDROID)
1132 else if (pItem->IsAndroidApp())
1133 {
1134 std::string appName = URIUtils::GetFileName(pItem->GetPath());
1135 CLog::Log(LOGDEBUG, "CGUIMediaWindow::OnClick Trying to run: {}", appName);
1136 return CXBMCApp::StartActivity(appName);
1137 }
1138 #endif
1139 else
1140 {
1141 SaveSelectedItemInHistory();
1142
1143 if (pItem->GetPath() == "newplaylist://")
1144 {
1145 m_vecItems->RemoveDiscCache(GetID());
1146 CServiceBroker::GetGUI()->GetWindowManager().ActivateWindow(WINDOW_MUSIC_PLAYLIST_EDITOR,"newplaylist://");
1147 return true;
1148 }
1149 else if (StringUtils::StartsWithNoCase(pItem->GetPath(), "newsmartplaylist://"))
1150 {
1151 m_vecItems->RemoveDiscCache(GetID());
1152 if (CGUIDialogSmartPlaylistEditor::NewPlaylist(pItem->GetPath().substr(19)))
1153 Refresh();
1154 return true;
1155 }
1156
1157 bool autoplay = m_guiState.get() && m_guiState->AutoPlayNextItem();
1158
1159 if (m_vecItems->IsPlugin())
1160 {
1161 CURL url(m_vecItems->GetPath());
1162 AddonPtr addon;
1163 if (CServiceBroker::GetAddonMgr().GetAddon(url.GetHostName(), addon, OnlyEnabled::CHOICE_YES))
1164 {
1165 const auto plugin = std::dynamic_pointer_cast<CPluginSource>(addon);
1166 if (plugin && plugin->Provides(CPluginSource::AUDIO))
1167 {
1168 CFileItemList items;
1169 std::unique_ptr<CGUIViewState> state(CGUIViewState::GetViewState(GetID(), items));
1170 autoplay = state.get() && state->AutoPlayNextItem();
1171 }
1172 }
1173 }
1174
1175 if (autoplay && !g_partyModeManager.IsEnabled())
1176 {
1177 return OnPlayAndQueueMedia(pItem, player);
1178 }
1179 else
1180 {
1181 return OnPlayMedia(iItem, player);
1182 }
1183 }
1184
1185 return false;
1186 }
1187
1188 bool CGUIMediaWindow::OnSelect(int item)
1189 {
1190 return OnClick(item);
1191 }
1192
1193 /*!
1194 * \brief Check disc or connection present
1195 *
1196 * Checks if there is a disc in the dvd drive and whether the
1197 * network is connected or not.
1198 */
1199 bool CGUIMediaWindow::HaveDiscOrConnection(const std::string& strPath, int iDriveType)
1200 {
1201 if (iDriveType==CMediaSource::SOURCE_TYPE_DVD)
1202 {
1203 if (!CServiceBroker::GetMediaManager().IsDiscInDrive(strPath))
1204 {
1205 HELPERS::ShowOKDialogText(CVariant{218}, CVariant{219});
1206 return false;
1207 }
1208 }
1209 else if (iDriveType==CMediaSource::SOURCE_TYPE_REMOTE)
1210 {
1211 //! @todo Handle not connected to a remote share
1212 if (!CServiceBroker::GetNetwork().IsConnected())
1213 {
1214 HELPERS::ShowOKDialogText(CVariant{220}, CVariant{221});
1215 return false;
1216 }
1217 }
1218
1219 return true;
1220 }
1221
1222 /*!
1223 * \brief Shows a standard error message for a given pItem.
1224 */
1225 void CGUIMediaWindow::ShowShareErrorMessage(CFileItem* pItem) const
1226 {
1227 if (!pItem->m_bIsShareOrDrive)
1228 return;
1229
1230 int idMessageText = 0;
1231 CURL url(pItem->GetPath());
1232
1233 if (url.IsProtocol("smb") && url.GetHostName().empty()) // smb workgroup
1234 idMessageText = 15303; // Workgroup not found
1235 else if (pItem->m_iDriveType == CMediaSource::SOURCE_TYPE_REMOTE || URIUtils::IsRemote(pItem->GetPath()))
1236 idMessageText = 15301; // Could not connect to network server
1237 else
1238 idMessageText = 15300; // Path not found or invalid
1239
1240 HELPERS::ShowOKDialogText(CVariant{220}, CVariant{idMessageText});
1241 }
1242
1243 /*!
1244 * \brief Go one directory up on list items
1245 *
1246 * The function goes up one level in the directory tree
1247 */
1248 bool CGUIMediaWindow::GoParentFolder()
1249 {
1250 if (m_vecItems->IsVirtualDirectoryRoot())
1251 return false;
1252
1253 if (URIUtils::PathEquals(m_vecItems->GetPath(), GetRootPath()))
1254 return false;
1255
1256 //m_history.DumpPathHistory();
1257
1258 const std::string currentPath = m_vecItems->GetPath();
1259 std::string parentPath = m_history.GetParentPath();
1260 // Check if a) the current folder is on the stack more than once, (parent is
1261 // often same as current), OR
1262 // b) the parent is an xml file (happens when ActivateWindow() called with
1263 // a node file) and so current path is the result of expanding the xml.
1264 // Keep going until there's nothing left or they dont match anymore.
1265 while (!parentPath.empty() &&
1266 (URIUtils::PathEquals(parentPath, currentPath, true) ||
1267 StringUtils::EndsWith(parentPath, ".xml/") || StringUtils::EndsWith(parentPath, ".xml")))
1268 {
1269 m_history.RemoveParentPath();
1270 parentPath = m_history.GetParentPath();
1271 }
1272
1273 // remove the current filter but only if the parent
1274 // item doesn't have a filter as well
1275 CURL filterUrl(m_strFilterPath);
1276 if (filterUrl.HasOption("filter"))
1277 {
1278 CURL parentUrl(m_history.GetParentPath(true));
1279 if (!parentUrl.HasOption("filter"))
1280 {
1281 // we need to overwrite m_strFilterPath because
1282 // Refresh() will set updateFilterPath to false
1283 m_strFilterPath.clear();
1284 Refresh();
1285 return true;
1286 }
1287 }
1288
1289 // pop directory path from the stack
1290 m_strFilterPath = m_history.GetParentPath(true);
1291 m_history.RemoveParentPath();
1292
1293 if (!Update(parentPath, false))
1294 return false;
1295
1296 // No items to show so go another level up
1297 if (!m_vecItems->GetPath().empty() && (m_filter.IsEmpty() ? m_vecItems->Size() : m_unfilteredItems->Size()) <= 0)
1298 {
1299 CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(2080), g_localizeStrings.Get(2081));
1300 return GoParentFolder();
1301 }
1302 return true;
1303 }
1304
1305 void CGUIMediaWindow::SaveSelectedItemInHistory()
1306 {
1307 int iItem = m_viewControl.GetSelectedItem();
1308 std::string strSelectedItem;
1309 if (iItem >= 0 && iItem < m_vecItems->Size())
1310 {
1311 CFileItemPtr pItem = m_vecItems->Get(iItem);
1312 GetDirectoryHistoryString(pItem.get(), strSelectedItem);
1313 }
1314
1315 m_history.SetSelectedItem(strSelectedItem, m_vecItems->GetPath(), iItem);
1316 }
1317
1318 void CGUIMediaWindow::RestoreSelectedItemFromHistory()
1319 {
1320 std::string strSelectedItem = m_history.GetSelectedItem(m_vecItems->GetPath());
1321
1322 if (!strSelectedItem.empty())
1323 {
1324 for (int i = 0; i < m_vecItems->Size(); ++i)
1325 {
1326 CFileItemPtr pItem = m_vecItems->Get(i);
1327 std::string strHistory;
1328 GetDirectoryHistoryString(pItem.get(), strHistory);
1329 // set selected item if equals with history
1330 if (strHistory == strSelectedItem)
1331 {
1332 m_viewControl.SetSelectedItem(i);
1333 return;
1334 }
1335 }
1336 }
1337
1338 // Exact item not found - maybe deleted, watched status change, filtered out, ...
1339 // Attempt to restore the position of the selection
1340 int selectedItemIndex = m_history.GetSelectedItemIndex(m_vecItems->GetPath());
1341 if (selectedItemIndex >= 0 && m_vecItems->Size() > 0)
1342 {
1343 int newIndex = std::min(selectedItemIndex, m_vecItems->Size() - 1);
1344 m_viewControl.SetSelectedItem(newIndex);
1345 return;
1346 }
1347
1348 // Fallback: select the first item
1349 m_viewControl.SetSelectedItem(0);
1350 }
1351
1352 /*!
1353 * \brief Get history string for given file item
1354 *
1355 * \note Override the function to change the default behavior on how
1356 * a selected item history should look like
1357 */
1358 void CGUIMediaWindow::GetDirectoryHistoryString(const CFileItem* pItem, std::string& strHistoryString) const
1359 {
1360 if (pItem->m_bIsShareOrDrive)
1361 {
1362 // We are in the virtual directory
1363
1364 // History string of the DVD drive
1365 // must be handled separately
1366 if (pItem->m_iDriveType == CMediaSource::SOURCE_TYPE_DVD)
1367 {
1368 // Remove disc label from item label
1369 // and use as history string, m_strPath
1370 // can change for new discs
1371 std::string strLabel = pItem->GetLabel();
1372 size_t nPosOpen = strLabel.find('(');
1373 size_t nPosClose = strLabel.rfind(')');
1374 if (nPosOpen != std::string::npos &&
1375 nPosClose != std::string::npos &&
1376 nPosClose > nPosOpen)
1377 {
1378 strLabel.erase(nPosOpen + 1, (nPosClose) - (nPosOpen + 1));
1379 strHistoryString = strLabel;
1380 }
1381 else
1382 strHistoryString = strLabel;
1383 }
1384 else
1385 {
1386 // Other items in virtual directory
1387 std::string strPath = pItem->GetPath();
1388 URIUtils::RemoveSlashAtEnd(strPath);
1389
1390 strHistoryString = pItem->GetLabel() + strPath;
1391 }
1392 }
1393 else if (pItem->GetEndOffset() > pItem->GetStartOffset() &&
1394 pItem->GetStartOffset() != STARTOFFSET_RESUME)
1395 {
1396 // Could be a cue item, all items of a cue share the same filename
1397 // so add the offsets to build the history string
1398 strHistoryString = StringUtils::Format("{}{}", pItem->GetStartOffset(), pItem->GetEndOffset());
1399 strHistoryString += pItem->GetPath();
1400 }
1401 else
1402 {
1403 // Normal directory items
1404 strHistoryString = pItem->GetPath();
1405 }
1406
1407 // remove any filter
1408 if (CanContainFilter(strHistoryString))
1409 strHistoryString = RemoveParameterFromPath(strHistoryString, "filter");
1410
1411 URIUtils::RemoveSlashAtEnd(strHistoryString);
1412 StringUtils::ToLower(strHistoryString);
1413 }
1414
1415 /*!
1416 * \brief Set history for path
1417 *
1418 * Call this function to create a directory history for the
1419 * path given by strDirectory.
1420 */
1421 void CGUIMediaWindow::SetHistoryForPath(const std::string& strDirectory)
1422 {
1423 // Make sure our shares are configured
1424 SetupShares();
1425 if (!strDirectory.empty())
1426 {
1427 // Build the directory history for default path
1428 std::string strPath, strParentPath;
1429 strPath = strDirectory;
1430 URIUtils::RemoveSlashAtEnd(strPath);
1431
1432 CFileItemList items;
1433 CURL url;
1434 GetDirectoryItems(url, items, UseFileDirectories());
1435
1436 m_history.ClearPathHistory();
1437
1438 bool originalPath = true;
1439 while (URIUtils::GetParentPath(strPath, strParentPath))
1440 {
1441 for (int i = 0; i < items.Size(); ++i)
1442 {
1443 CFileItemPtr pItem = items[i];
1444 std::string path(pItem->GetPath());
1445 URIUtils::RemoveSlashAtEnd(path);
1446 if (URIUtils::PathEquals(path, strPath))
1447 {
1448 std::string strHistory;
1449 GetDirectoryHistoryString(pItem.get(), strHistory);
1450 m_history.SetSelectedItem(strHistory, "");
1451 URIUtils::AddSlashAtEnd(strPath);
1452 m_history.AddPathFront(strPath);
1453 m_history.AddPathFront("");
1454
1455 //m_history.DumpPathHistory();
1456 return ;
1457 }
1458 }
1459
1460 if (URIUtils::IsVideoDb(strPath))
1461 {
1462 CURL url(strParentPath);
1463 url.SetOptions(""); // clear any URL options from recreated parent path
1464 strParentPath = url.Get();
1465 }
1466
1467 // set the original path exactly as it was passed in
1468 if (URIUtils::PathEquals(strPath, strDirectory, true))
1469 strPath = strDirectory;
1470 else
1471 URIUtils::AddSlashAtEnd(strPath);
1472
1473 m_history.AddPathFront(strPath, originalPath ? m_strFilterPath : "");
1474 m_history.SetSelectedItem(strPath, strParentPath);
1475 originalPath = false;
1476 strPath = strParentPath;
1477 URIUtils::RemoveSlashAtEnd(strPath);
1478 }
1479 }
1480 else
1481 m_history.ClearPathHistory();
1482
1483 //m_history.DumpPathHistory();
1484 }
1485
1486 /*!
1487 * \brief On media play
1488 *
1489 * \note Override if you want to change the default behavior, what is done
1490 * when the user clicks on a file.
1491 *
1492 * This function is called by OnClick()
1493 */
1494 bool CGUIMediaWindow::OnPlayMedia(int iItem, const std::string &player)
1495 {
1496 // Reset Playlistplayer, playback started now does
1497 // not use the playlistplayer.
1498 CServiceBroker::GetPlaylistPlayer().Reset();
1499 CServiceBroker::GetPlaylistPlayer().SetCurrentPlaylist(PLAYLIST::TYPE_NONE);
1500 CFileItemPtr pItem=m_vecItems->Get(iItem);
1501
1502 CLog::Log(LOGDEBUG, "{} {}", __FUNCTION__, CURL::GetRedacted(pItem->GetPath()));
1503
1504 bool bResult = false;
1505 if (pItem->IsInternetStream() || pItem->IsPlayList())
1506 bResult = g_application.PlayMedia(*pItem, player, m_guiState->GetPlaylist());
1507 else
1508 bResult = g_application.PlayFile(*pItem, player);
1509
1510 if (pItem->GetStartOffset() == STARTOFFSET_RESUME)
1511 pItem->SetStartOffset(0);
1512
1513 return bResult;
1514 }
1515
1516 /*!
1517 * \brief On play and media queue
1518 *
1519 * \note Override if you want to change the default behavior of what is done
1520 * when the user clicks on a file in a "folder" with similar files.
1521 *
1522 * This function is called by OnClick()
1523 */
1524 bool CGUIMediaWindow::OnPlayAndQueueMedia(const CFileItemPtr& item, const std::string& player)
1525 {
1526 //play and add current directory to temporary playlist
1527 PLAYLIST::Id playlistId = m_guiState->GetPlaylist();
1528 if (playlistId != PLAYLIST::TYPE_NONE)
1529 {
1530 CServiceBroker::GetPlaylistPlayer().ClearPlaylist(playlistId);
1531 CServiceBroker::GetPlaylistPlayer().Reset();
1532 int mediaToPlay = 0;
1533
1534 // first try to find mainDVD file (VIDEO_TS.IFO).
1535 // If we find this we should not allow to queue VOB files
1536 std::string mainDVD;
1537 for (int i = 0; i < m_vecItems->Size(); i++)
1538 {
1539 std::string path = URIUtils::GetFileName(m_vecItems->Get(i)->GetDynPath());
1540 if (StringUtils::EqualsNoCase(path, "VIDEO_TS.IFO"))
1541 {
1542 mainDVD = path;
1543 break;
1544 }
1545 }
1546
1547 // now queue...
1548 for ( int i = 0; i < m_vecItems->Size(); i++ )
1549 {
1550 CFileItemPtr nItem = m_vecItems->Get(i);
1551
1552 if (nItem->m_bIsFolder)
1553 continue;
1554
1555 if (!nItem->IsZIP() && !nItem->IsRAR() && (!nItem->IsDVDFile() || (URIUtils::GetFileName(nItem->GetDynPath()) == mainDVD)))
1556 CServiceBroker::GetPlaylistPlayer().Add(playlistId, nItem);
1557
1558 if (item->IsSamePath(nItem.get()))
1559 { // item that was clicked
1560 mediaToPlay = CServiceBroker::GetPlaylistPlayer().GetPlaylist(playlistId).size() - 1;
1561 }
1562 }
1563
1564 // Save current window and directory to know where the selected item was
1565 if (m_guiState)
1566 m_guiState->SetPlaylistDirectory(m_vecItems->GetPath());
1567
1568 // figure out where we start playback
1569 if (CServiceBroker::GetPlaylistPlayer().IsShuffled(playlistId))
1570 {
1571 int iIndex =
1572 CServiceBroker::GetPlaylistPlayer().GetPlaylist(playlistId).FindOrder(mediaToPlay);
1573 CServiceBroker::GetPlaylistPlayer().GetPlaylist(playlistId).Swap(0, iIndex);
1574 mediaToPlay = 0;
1575 }
1576
1577 // play
1578 CServiceBroker::GetPlaylistPlayer().SetCurrentPlaylist(playlistId);
1579 CServiceBroker::GetPlaylistPlayer().Play(mediaToPlay, player);
1580 }
1581 return true;
1582 }
1583
1584 /*!
1585 * \brief Update file list
1586 *
1587 * Synchronize the fileitems with the playlistplayer
1588 * also recreates the playlist of the playlistplayer based
1589 * on the fileitems of the window
1590 */
1591 void CGUIMediaWindow::UpdateFileList()
1592 {
1593 int nItem = m_viewControl.GetSelectedItem();
1594 std::string strSelected;
1595 if (nItem >= 0)
1596 strSelected = m_vecItems->Get(nItem)->GetPath();
1597
1598 FormatAndSort(*m_vecItems);
1599 UpdateButtons();
1600
1601 m_viewControl.SetItems(*m_vecItems);
1602 m_viewControl.SetSelectedItem(strSelected);
1603
1604 // set the currently playing item as selected, if its in this directory
1605 if (m_guiState.get() && m_guiState->IsCurrentPlaylistDirectory(m_vecItems->GetPath()))
1606 {
1607 PLAYLIST::Id playlistId = m_guiState->GetPlaylist();
1608 int nSong = CServiceBroker::GetPlaylistPlayer().GetCurrentItemIdx();
1609 CFileItem playlistItem;
1610 if (nSong > -1 && playlistId != PLAYLIST::TYPE_NONE)
1611 playlistItem = *CServiceBroker::GetPlaylistPlayer().GetPlaylist(playlistId)[nSong];
1612
1613 CServiceBroker::GetPlaylistPlayer().ClearPlaylist(playlistId);
1614 CServiceBroker::GetPlaylistPlayer().Reset();
1615
1616 for (int i = 0; i < m_vecItems->Size(); i++)
1617 {
1618 CFileItemPtr pItem = m_vecItems->Get(i);
1619 if (pItem->m_bIsFolder)
1620 continue;
1621
1622 if (!pItem->IsPlayList() && !pItem->IsZIP() && !pItem->IsRAR())
1623 CServiceBroker::GetPlaylistPlayer().Add(playlistId, pItem);
1624
1625 if (pItem->GetPath() == playlistItem.GetPath() &&
1626 pItem->GetStartOffset() == playlistItem.GetStartOffset())
1627 CServiceBroker::GetPlaylistPlayer().SetCurrentItemIdx(
1628 CServiceBroker::GetPlaylistPlayer().GetPlaylist(playlistId).size() - 1);
1629 }
1630 }
1631 }
1632
1633 void CGUIMediaWindow::OnDeleteItem(int iItem)
1634 {
1635 if ( iItem < 0 || iItem >= m_vecItems->Size()) return;
1636 CFileItemPtr item = m_vecItems->Get(iItem);
1637
1638 if (item->IsPlayList())
1639 item->m_bIsFolder = false;
1640
1641 const std::shared_ptr<CProfileManager> profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
1642
1643 if (profileManager->GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && profileManager->GetCurrentProfile().filesLocked())
1644 {
1645 if (!g_passwordManager.IsMasterLockUnlocked(true))
1646 return;
1647 }
1648
1649 CGUIComponent *gui = CServiceBroker::GetGUI();
1650 if (gui && gui->ConfirmDelete(item->GetPath()))
1651 {
1652 if (!CFileUtils::DeleteItem(item))
1653 return;
1654 }
1655 else
1656 return;
1657
1658 Refresh(true);
1659 m_viewControl.SetSelectedItem(iItem);
1660 }
1661
1662 void CGUIMediaWindow::OnRenameItem(int iItem)
1663 {
1664 if (iItem < 0 || iItem >= m_vecItems->Size())
1665 return;
1666
1667 const std::shared_ptr<CProfileManager> profileManager = CServiceBroker::GetSettingsComponent()->GetProfileManager();
1668
1669 if (profileManager->GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && profileManager->GetCurrentProfile().filesLocked())
1670 {
1671 if (!g_passwordManager.IsMasterLockUnlocked(true))
1672 return;
1673 }
1674
1675 if (!CFileUtils::RenameFile(m_vecItems->Get(iItem)->GetPath()))
1676 return;
1677
1678 Refresh(true);
1679 m_viewControl.SetSelectedItem(iItem);
1680 }
1681
1682 void CGUIMediaWindow::OnInitWindow()
1683 {
1684 // initial fetch is done unthreaded to ensure the items are setup prior to skin animations kicking off
1685 m_backgroundLoad = false;
1686
1687 // the start directory may change during Refresh
1688 bool updateStartDirectory = URIUtils::PathEquals(m_vecItems->GetPath(), m_startDirectory, true);
1689
1690 // we have python scripts hooked in everywhere :(
1691 // those scripts may open windows and we can't open a window
1692 // while opening this one.
1693 // for plugin sources delay call to Refresh
1694 if (!URIUtils::IsPlugin(m_vecItems->GetPath()))
1695 {
1696 Refresh();
1697 }
1698 else
1699 {
1700 CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0, 0, WINDOW_INVALID, PLUGIN_REFRESH_DELAY);
1701 CServiceBroker::GetGUI()->GetWindowManager().SendThreadMessage(msg, GetID());
1702 }
1703
1704 if (updateStartDirectory)
1705 {
1706 // reset the start directory to the path of the items
1707 m_startDirectory = m_vecItems->GetPath();
1708
1709 // reset the history based on the path of the items
1710 SetHistoryForPath(m_startDirectory);
1711 }
1712
1713 m_backgroundLoad = true;
1714
1715 CGUIWindow::OnInitWindow();
1716 }
1717
1718 void CGUIMediaWindow::SaveControlStates()
1719 {
1720 CGUIWindow::SaveControlStates();
1721 SaveSelectedItemInHistory();
1722 }
1723
1724 void CGUIMediaWindow::RestoreControlStates()
1725 {
1726 CGUIWindow::RestoreControlStates();
1727 RestoreSelectedItemFromHistory();
1728 }
1729
1730 CGUIControl *CGUIMediaWindow::GetFirstFocusableControl(int id)
1731 {
1732 if (m_viewControl.HasControl(id))
1733 id = m_viewControl.GetCurrentControl();
1734 return CGUIWindow::GetFirstFocusableControl(id);
1735 }
1736
1737 void CGUIMediaWindow::SetupShares()
1738 {
1739 // Setup shares and filemasks for this window
1740 CFileItemList items;
1741 CGUIViewState* viewState=CGUIViewState::GetViewState(GetID(), items);
1742 if (viewState)
1743 {
1744 m_rootDir.SetMask(viewState->GetExtensions());
1745 m_rootDir.SetSources(viewState->GetSources());
1746 delete viewState;
1747 }
1748 }
1749
1750 bool CGUIMediaWindow::OnPopupMenu(int itemIdx)
1751 {
1752 auto InRange = [](size_t i, std::pair<size_t, size_t> range){ return i >= range.first && i < range.second; };
1753
1754 if (itemIdx < 0 || itemIdx >= m_vecItems->Size())
1755 return false;
1756
1757 auto item = m_vecItems->Get(itemIdx);
1758 if (!item)
1759 return false;
1760
1761 CContextButtons buttons;
1762
1763 //Add items from plugin
1764 {
1765 int i = 0;
1766 while (item->HasProperty(StringUtils::Format("contextmenulabel({})", i)))
1767 {
1768 buttons.emplace_back(
1769 ~buttons.size(),
1770 item->GetProperty(StringUtils::Format("contextmenulabel({})", i)).asString());
1771 ++i;
1772 }
1773 }
1774 auto pluginMenuRange = std::make_pair(static_cast<size_t>(0), buttons.size());
1775
1776 //Add the global menu
1777 auto globalMenu = CServiceBroker::GetContextMenuManager().GetItems(*item, CContextMenuManager::MAIN);
1778 auto globalMenuRange = std::make_pair(buttons.size(), buttons.size() + globalMenu.size());
1779 for (const auto& menu : globalMenu)
1780 buttons.emplace_back(~buttons.size(), menu->GetLabel(*item));
1781
1782 //Add legacy items from windows
1783 auto buttonsSize = buttons.size();
1784 GetContextButtons(itemIdx, buttons);
1785 auto windowMenuRange = std::make_pair(buttonsSize, buttons.size());
1786
1787 //Add addon menus
1788 auto addonMenu = CServiceBroker::GetContextMenuManager().GetAddonItems(*item, CContextMenuManager::MAIN);
1789 auto addonMenuRange = std::make_pair(buttons.size(), buttons.size() + addonMenu.size());
1790 for (const auto& menu : addonMenu)
1791 buttons.emplace_back(~buttons.size(), menu->GetLabel(*item));
1792
1793 if (buttons.empty())
1794 return true;
1795
1796 int idx = CGUIDialogContextMenu::Show(buttons);
1797 if (idx < 0 || idx >= static_cast<int>(buttons.size()))
1798 return false;
1799
1800 if (InRange(static_cast<size_t>(idx), pluginMenuRange))
1801 {
1802 bool saveVal = m_backgroundLoad;
1803 m_backgroundLoad = false;
1804 CServiceBroker::GetAppMessenger()->SendMsg(
1805 TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr,
1806 item->GetProperty(StringUtils::Format("contextmenuaction({})", idx - pluginMenuRange.first))
1807 .asString());
1808 m_backgroundLoad = saveVal;
1809 return true;
1810 }
1811
1812 if (InRange(idx, windowMenuRange))
1813 return OnContextButton(itemIdx, static_cast<CONTEXT_BUTTON>(buttons[idx].first));
1814
1815 if (InRange(idx, globalMenuRange))
1816 return CONTEXTMENU::LoopFrom(*globalMenu[idx - globalMenuRange.first], item);
1817
1818 return CONTEXTMENU::LoopFrom(*addonMenu[idx - addonMenuRange.first], item);
1819 }
1820
1821 const CGUIViewState *CGUIMediaWindow::GetViewState() const
1822 {
1823 return m_guiState.get();
1824 }
1825
1826 const CFileItemList& CGUIMediaWindow::CurrentDirectory() const
1827 {
1828 return *m_vecItems;
1829 }
1830
1831 bool CGUIMediaWindow::WaitForNetwork() const
1832 {
1833 if (CServiceBroker::GetNetwork().IsAvailable())
1834 return true;
1835
1836 CGUIDialogProgress *progress = CServiceBroker::GetGUI()->GetWindowManager().GetWindow<CGUIDialogProgress>(WINDOW_DIALOG_PROGRESS);
1837 if (!progress)
1838 return true;
1839
1840 CURL url(m_vecItems->GetPath());
1841 progress->SetHeading(CVariant{1040}); // Loading Directory
1842 progress->SetLine(1, CVariant{url.GetWithoutUserDetails()});
1843 progress->ShowProgressBar(false);
1844 progress->Open();
1845 while (!CServiceBroker::GetNetwork().IsAvailable())
1846 {
1847 progress->Progress();
1848 if (progress->IsCanceled())
1849 {
1850 progress->Close();
1851 return false;
1852 }
1853 }
1854 progress->Close();
1855 return true;
1856 }
1857
1858 void CGUIMediaWindow::UpdateFilterPath(const std::string &strDirectory, const CFileItemList &items, bool updateFilterPath)
1859 {
1860 bool canfilter = CanContainFilter(strDirectory);
1861
1862 std::string filter;
1863 CURL url(strDirectory);
1864 if (canfilter && url.HasOption("filter"))
1865 filter = url.GetOption("filter");
1866
1867 // only set the filter path if it hasn't been marked
1868 // as preset or if it's empty
1869 if (updateFilterPath || m_strFilterPath.empty())
1870 {
1871 if (items.HasProperty(PROPERTY_PATH_DB))
1872 m_strFilterPath = items.GetProperty(PROPERTY_PATH_DB).asString();
1873 else
1874 m_strFilterPath = items.GetPath();
1875 }
1876
1877 // maybe the filter path can contain a filter
1878 if (!canfilter && CanContainFilter(m_strFilterPath))
1879 canfilter = true;
1880
1881 // check if the filter path contains a filter
1882 CURL filterPathUrl(m_strFilterPath);
1883 if (canfilter && filter.empty())
1884 {
1885 if (filterPathUrl.HasOption("filter"))
1886 filter = filterPathUrl.GetOption("filter");
1887 }
1888
1889 // check if there is a filter and re-apply it
1890 if (canfilter && !filter.empty())
1891 {
1892 if (!m_filter.LoadFromJson(filter))
1893 {
1894 CLog::Log(LOGWARNING,
1895 "CGUIMediaWindow::UpdateFilterPath(): unable to load existing filter ({})", filter);
1896 m_filter.Reset();
1897 m_strFilterPath = m_vecItems->GetPath();
1898 }
1899 else
1900 {
1901 // add the filter to the filter path
1902 filterPathUrl.SetOption("filter", filter);
1903 m_strFilterPath = filterPathUrl.Get();
1904 }
1905 }
1906 }
1907
1908 void CGUIMediaWindow::OnFilterItems(const std::string &filter)
1909 {
1910 m_viewControl.Clear();
1911
1912 CFileItemList items;
1913 items.Copy(*m_vecItems, false); // use the original path - it'll likely be relied on for other things later.
1914 items.Append(*m_unfilteredItems);
1915 bool filtered = GetFilteredItems(filter, items);
1916
1917 m_vecItems->ClearItems();
1918 // we need to clear the sort state and re-sort the items
1919 m_vecItems->ClearSortState();
1920 m_vecItems->Append(items);
1921
1922 // if the filter has changed, get the new filter path
1923 if (filtered && m_canFilterAdvanced)
1924 {
1925 if (items.HasProperty(PROPERTY_PATH_DB))
1926 m_strFilterPath = items.GetProperty(PROPERTY_PATH_DB).asString();
1927 // only set m_strFilterPath if it hasn't been set before
1928 // otherwise we might overwrite it with a non-filter path
1929 // in case GetFilteredItems() returns true even though no
1930 // db-based filter (e.g. watched filter) has been applied
1931 else if (m_strFilterPath.empty())
1932 m_strFilterPath = items.GetPath();
1933 }
1934
1935 GetGroupedItems(*m_vecItems);
1936 FormatAndSort(*m_vecItems);
1937
1938 CFileItemPtr currentItem;
1939 std::string currentItemPath;
1940 int item = m_viewControl.GetSelectedItem();
1941 if (item >= 0 && item < m_vecItems->Size())
1942 {
1943 currentItem = m_vecItems->Get(item);
1944 currentItemPath = currentItem->GetPath();
1945 }
1946
1947 // get the "filter" option
1948 std::string filterOption;
1949 CURL filterUrl(m_strFilterPath);
1950 if (filterUrl.HasOption("filter"))
1951 filterOption = filterUrl.GetOption("filter");
1952
1953 // apply the "filter" option to any folder item so that
1954 // the filter can be passed down to the sub-directory
1955 for (int index = 0; index < m_vecItems->Size(); index++)
1956 {
1957 CFileItemPtr pItem = m_vecItems->Get(index);
1958 // if the item is a folder we need to copy the path of
1959 // the filtered item to be able to keep the applied filters
1960 if (pItem->m_bIsFolder)
1961 {
1962 CURL itemUrl(pItem->GetPath());
1963 if (!filterOption.empty())
1964 itemUrl.SetOption("filter", filterOption);
1965 else
1966 itemUrl.RemoveOption("filter");
1967 pItem->SetPath(itemUrl.Get());
1968 }
1969 }
1970
1971 SetProperty("filter", filter);
1972 if (filtered && m_canFilterAdvanced)
1973 {
1974 // to be able to select the same item as before we need to adjust
1975 // the path of the item i.e. add or remove the "filter=" URL option
1976 // but that's only necessary for folder items
1977 if (currentItem.get() && currentItem->m_bIsFolder)
1978 {
1979 CURL curUrl(currentItemPath), newUrl(m_strFilterPath);
1980 if (newUrl.HasOption("filter"))
1981 curUrl.SetOption("filter", newUrl.GetOption("filter"));
1982 else if (curUrl.HasOption("filter"))
1983 curUrl.RemoveOption("filter");
1984
1985 currentItemPath = curUrl.Get();
1986 }
1987 }
1988
1989 // The idea here is to ensure we have something to focus if our file list
1990 // is empty. As such, this check MUST be last and ignore the hide parent
1991 // fileitems settings.
1992 if (m_vecItems->IsEmpty())
1993 {
1994 CFileItemPtr pItem(new CFileItem(".."));
1995 pItem->SetPath(m_history.GetParentPath());
1996 pItem->m_bIsFolder = true;
1997 pItem->m_bIsShareOrDrive = false;
1998 m_vecItems->AddFront(pItem, 0);
1999 }
2000
2001 // and update our view control + buttons
2002 m_viewControl.SetItems(*m_vecItems);
2003 m_viewControl.SetSelectedItem(currentItemPath);
2004 }
2005
2006 bool CGUIMediaWindow::GetFilteredItems(const std::string &filter, CFileItemList &items)
2007 {
2008 bool result = false;
2009 if (m_canFilterAdvanced)
2010 result = GetAdvanceFilteredItems(items);
2011
2012 std::string trimmedFilter(filter);
2013 StringUtils::TrimLeft(trimmedFilter);
2014 StringUtils::ToLower(trimmedFilter);
2015
2016 if (trimmedFilter.empty())
2017 return result;
2018
2019 CFileItemList filteredItems(items.GetPath()); // use the original path - it'll likely be relied on for other things later.
2020 bool numericMatch = StringUtils::IsNaturalNumber(trimmedFilter);
2021 for (int i = 0; i < items.Size(); i++)
2022 {
2023 CFileItemPtr item = items.Get(i);
2024 if (item->IsParentFolder())
2025 {
2026 filteredItems.Add(item);
2027 continue;
2028 }
2029 //! @todo Need to update this to get all labels, ideally out of the displayed info (ie from m_layout and m_focusedLayout)
2030 //! though that isn't practical. Perhaps a better idea would be to just grab the info that we should filter on based on
2031 //! where we are in the library tree.
2032 //! Another idea is tying the filter string to the current level of the tree, so that going deeper disables the filter,
2033 //! but it's re-enabled on the way back out.
2034 std::string match;
2035 /* if (item->GetFocusedLayout())
2036 match = item->GetFocusedLayout()->GetAllText();
2037 else if (item->GetLayout())
2038 match = item->GetLayout()->GetAllText();
2039 else*/
2040 match = item->GetLabel(); // Filter label only for now
2041
2042 if (numericMatch)
2043 StringUtils::WordToDigits(match);
2044
2045 size_t pos = StringUtils::FindWords(match.c_str(), trimmedFilter.c_str());
2046 if (pos != std::string::npos)
2047 filteredItems.Add(item);
2048 }
2049
2050 items.ClearItems();
2051 items.Append(filteredItems);
2052
2053 return items.GetObjectCount() > 0;
2054 }
2055
2056 bool CGUIMediaWindow::GetAdvanceFilteredItems(CFileItemList &items)
2057 {
2058 // don't run the advanced filter if the filter is empty
2059 // and there hasn't been a filter applied before which
2060 // would have to be removed
2061 CURL url(m_strFilterPath);
2062 if (m_filter.IsEmpty() && !url.HasOption("filter"))
2063 return false;
2064
2065 CFileItemList resultItems;
2066 XFILE::CSmartPlaylistDirectory::GetDirectory(m_filter, resultItems, m_strFilterPath, true);
2067
2068 // put together a lookup map for faster path comparison
2069 std::map<std::string, CFileItemPtr> lookup;
2070 for (int j = 0; j < resultItems.Size(); j++)
2071 {
2072 std::string itemPath = CURL(resultItems[j]->GetPath()).GetWithoutOptions();
2073 StringUtils::ToLower(itemPath);
2074
2075 lookup[itemPath] = resultItems[j];
2076 }
2077
2078 // loop through all the original items and find
2079 // those which are still part of the filter
2080 CFileItemList filteredItems;
2081 for (int i = 0; i < items.Size(); i++)
2082 {
2083 CFileItemPtr item = items.Get(i);
2084 if (item->IsParentFolder())
2085 {
2086 filteredItems.Add(item);
2087 continue;
2088 }
2089
2090 // check if the item is part of the resultItems list
2091 // by comparing their paths (but ignoring any special
2092 // options because they differ from filter to filter)
2093 std::string path = CURL(item->GetPath()).GetWithoutOptions();
2094 StringUtils::ToLower(path);
2095
2096 std::map<std::string, CFileItemPtr>::iterator itItem = lookup.find(path);
2097 if (itItem != lookup.end())
2098 {
2099 // add the item to the list of filtered items
2100 filteredItems.Add(item);
2101
2102 // remove the item from the lists
2103 resultItems.Remove(itItem->second.get());
2104 lookup.erase(itItem);
2105 }
2106 }
2107
2108 if (resultItems.Size() > 0)
2109 CLog::Log(LOGWARNING, "CGUIMediaWindow::GetAdvanceFilteredItems(): {} unknown items",
2110 resultItems.Size());
2111
2112 items.ClearItems();
2113 items.Append(filteredItems);
2114 items.SetPath(resultItems.GetPath());
2115 if (resultItems.HasProperty(PROPERTY_PATH_DB))
2116 items.SetProperty(PROPERTY_PATH_DB, resultItems.GetProperty(PROPERTY_PATH_DB));
2117 return true;
2118 }
2119
2120 bool CGUIMediaWindow::IsFiltered()
2121 {
2122 return (!m_canFilterAdvanced && !GetProperty("filter").empty()) ||
2123 (m_canFilterAdvanced && !m_filter.IsEmpty());
2124 }
2125
2126 bool CGUIMediaWindow::IsSameStartFolder(const std::string &dir)
2127 {
2128 const std::string startFolder = GetStartFolder(dir);
2129 return URIUtils::PathHasParent(m_vecItems->GetPath(), startFolder);
2130 }
2131
2132 bool CGUIMediaWindow::Filter(bool advanced /* = true */)
2133 {
2134 // basic filtering
2135 if (!m_canFilterAdvanced || !advanced)
2136 {
2137 const CGUIControl *btnFilter = GetControl(CONTROL_BTN_FILTER);
2138 if (btnFilter && btnFilter->GetControlType() == CGUIControl::GUICONTROL_EDIT)
2139 { // filter updated
2140 CGUIMessage selected(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_BTN_FILTER);
2141 OnMessage(selected);
2142 OnFilterItems(selected.GetLabel());
2143 UpdateButtons();
2144 return true;
2145 }
2146 if (GetProperty("filter").empty())
2147 {
2148 std::string filter = GetProperty("filter").asString();
2149 CGUIKeyboardFactory::ShowAndGetFilter(filter, false);
2150 SetProperty("filter", filter);
2151 }
2152 else
2153 {
2154 OnFilterItems("");
2155 UpdateButtons();
2156 }
2157 }
2158 // advanced filtering
2159 else
2160 CGUIDialogMediaFilter::ShowAndEditMediaFilter(m_strFilterPath, m_filter);
2161
2162 return true;
2163 }
2164
2165 std::string CGUIMediaWindow::GetStartFolder(const std::string &dir)
2166 {
2167 if (StringUtils::EqualsNoCase(dir, "$root") ||
2168 StringUtils::EqualsNoCase(dir, "root"))
2169 return "";
2170
2171 // Let plugins handle their own urls themselves
2172 if (StringUtils::StartsWith(dir, "plugin://"))
2173 return dir;
2174
2175 //! @todo This ifdef block probably belongs somewhere else. Move it to a better place!
2176 #if defined(TARGET_ANDROID)
2177 // Hack for Android items (numbered id's) on the leanback screen
2178 std::string path;
2179 std::string fileName;
2180 URIUtils::Split(dir, path, fileName);
2181 URIUtils::RemoveExtension(fileName);
2182 if (StringUtils::IsInteger(fileName))
2183 return path;
2184 #endif
2185
2186 return dir;
2187 }
2188
2189 std::string CGUIMediaWindow::RemoveParameterFromPath(const std::string &strDirectory, const std::string &strParameter)
2190 {
2191 CURL url(strDirectory);
2192 if (url.HasOption(strParameter))
2193 {
2194 url.RemoveOption(strParameter);
2195 return url.Get();
2196 }
2197
2198 return strDirectory;
2199 }
2200
2201 bool CGUIMediaWindow::ProcessRenderLoop(bool renderOnly)
2202 {
2203 return CServiceBroker::GetGUI()->GetWindowManager().ProcessRenderLoop(renderOnly);
2204 }
2205
2206 bool CGUIMediaWindow::GetDirectoryItems(CURL &url, CFileItemList &items, bool useDir)
2207 {
2208 if (m_backgroundLoad)
2209 {
2210 bool ret = true;
2211 CGetDirectoryItems getItems(m_rootDir, url, items, useDir);
2212
2213 if (!CGUIDialogBusy::Wait(&getItems, 100, true))
2214 {
2215 // cancelled
2216 ret = false;
2217 }
2218 else if (!getItems.m_result)
2219 {
2220 if (CServiceBroker::GetAppMessenger()->IsProcessThread() && m_rootDir.GetDirImpl() &&
2221 !m_rootDir.GetDirImpl()->ProcessRequirements())
2222 {
2223 ret = false;
2224 }
2225 else if (!CGUIDialogBusy::Wait(&getItems, 100, true) || !getItems.m_result)
2226 {
2227 ret = false;
2228 }
2229 }
2230
2231 m_rootDir.ReleaseDirImpl();
2232 return ret;
2233 }
2234 else
2235 {
2236 return m_rootDir.GetDirectory(url, items, useDir, false);
2237 }
2238 }