More file selector fixes

Fix a freeze that occurs when you move or delete a file in the
file manager
Make file sort buttons work again

Change-Id: Ifcb68edf3c29c475946d538748729485d0840842
diff --git a/gui/fileselector.cpp b/gui/fileselector.cpp
index 4da72d8..37eeed2 100644
--- a/gui/fileselector.cpp
+++ b/gui/fileselector.cpp
@@ -378,13 +378,6 @@
 
 int GUIFileSelector::Render(void)
 {
-	// Update the file list if needed
-	if (updateFileList) {
-		string value;
-		DataManager::GetValue(mPathVar, value);
-		GetFileList(value);
-		updateFileList = false;
-	}
 	// First step, fill background
 	gr_color(mBackgroundColor.red, mBackgroundColor.green, mBackgroundColor.blue, 255);
 	gr_fill(mRenderX, mRenderY + mHeaderH, mRenderW, mRenderH - mHeaderH);
@@ -397,6 +390,23 @@
 		gr_blit(mBackground->GetResource(), 0, 0, mBackgroundW, mBackgroundH, mBackgroundX, mBackgroundY);
 	}
 
+	// Update the file list if needed
+	pthread_mutex_lock(&updateFileListmutex);
+	if (updateFileList) {
+		pthread_mutex_unlock(&updateFileListmutex);
+		string value;
+		DataManager::GetValue(mPathVar, value);
+		if (GetFileList(value) == 0) {
+			pthread_mutex_lock(&updateFileListmutex);
+			updateFileList = false;
+			pthread_mutex_unlock(&updateFileListmutex);
+		} else {
+			return 0;
+		}
+	} else {
+		pthread_mutex_unlock(&updateFileListmutex);
+	}
+
 	// This tells us how many lines we can actually render
 	int lines = (mRenderH - mHeaderH) / (actualLineHeight);
 	int line;
@@ -551,7 +561,12 @@
 		gr_fill(mFastScrollRectX, mFastScrollRectY, mFastScrollRectW, mFastScrollRectH);
 	}
 
-	mUpdate = 0;
+	// If a change came in during the render then we need to do another redraw so leave mUpdate alone if updateFileList is true.
+	pthread_mutex_lock(&updateFileListmutex);
+	if (!updateFileList) {
+		mUpdate = 0;
+	}
+	pthread_mutex_unlock(&updateFileListmutex);
 	return 0;
 }
 
@@ -843,11 +858,12 @@
 	}
 	if (varName == mPathVar || varName == mSortVariable)
 	{
-		// If needed, wait for render to finish before continuing or the list change may not register
-		while (updateFileList || mUpdate) {
-			usleep(500);
+		if (varName == mSortVariable) {
+			DataManager::GetValue(mSortVariable, mSortOrder);
 		}
+		pthread_mutex_lock(&updateFileListmutex);
 		updateFileList = true;
+		pthread_mutex_unlock(&updateFileListmutex);
 		mStart = 0;
 		scrollingY = 0;
 		scrollingSpeed = 0;
@@ -988,9 +1004,11 @@
 {
 	if (inFocus)
 	{
+		pthread_mutex_lock(&updateFileListmutex);
 		updateFileList = true;
+		pthread_mutex_unlock(&updateFileListmutex);
 		scrollingY = 0;
 		scrollingSpeed = 0;
 		mUpdate = 1;
 	}
-}
+}
\ No newline at end of file
diff --git a/gui/objects.hpp b/gui/objects.hpp
index 3a39fe5..047b66b 100644
--- a/gui/objects.hpp
+++ b/gui/objects.hpp
@@ -496,6 +496,7 @@
 	COLOR mFontHighlightColor;
 	int startSelection;
 	bool updateFileList;
+	pthread_mutex_t updateFileListmutex;
 };
 
 class GUIListBox : public RenderObject, public ActionObject