Skip to content

Commit

Permalink
#5175: FileChooser pre-selects the correct file filter based on a non…
Browse files Browse the repository at this point in the history
…-empty existing filename
  • Loading branch information
codereader committed Apr 24, 2020
1 parent 77c146f commit ced0c50
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
41 changes: 41 additions & 0 deletions libs/wxutil/FileChooser.cpp
Expand Up @@ -17,6 +17,11 @@
namespace wxutil
{

namespace
{
const char* const WILDCARD_EXTENSION = "*";
}

FileChooser::FileChooser(const std::string& title,
bool open,
const std::string& fileType,
Expand Down Expand Up @@ -84,6 +89,7 @@ void FileChooser::construct()

filter.caption = format->getMapFormatName() + " " + pattern.name + " (" + pattern.pattern + ")";
filter.filter = pattern.pattern;
filter.extension = pattern.extension;
filter.mapFormatName = format->getMapFormatName();

_fileFilters.push_back(filter);
Expand All @@ -102,6 +108,7 @@ void FileChooser::construct()

filter.caption = pattern.name + " (" + pattern.pattern + ")";
filter.filter = pattern.pattern;
filter.extension = pattern.extension;

// Pre-select the filter matching the default extension
if (pattern.extension == _defaultExt)
Expand All @@ -120,6 +127,7 @@ void FileChooser::construct()

filter.caption = _("All Files (*.*)");
filter.filter = "*.*";
filter.extension = WILDCARD_EXTENSION;

_fileFilters.push_back(filter);

Expand Down Expand Up @@ -158,6 +166,7 @@ void FileChooser::setCurrentPath(const std::string& path)
if (!_file.empty())
{
_dialog->SetFilename(_file);
selectFilterIndexFromFilename(_file);
}
}

Expand All @@ -168,6 +177,38 @@ void FileChooser::setCurrentFile(const std::string& file)
if (!_open)
{
_dialog->SetFilename(_file);
selectFilterIndexFromFilename(_file);
}
}

void FileChooser::selectFilterIndexFromFilename(const std::string& filename)
{
if (filename.empty())
{
return;
}

auto ext = os::getExtension(filename);
std::size_t wildCardIndex = std::numeric_limits<std::size_t>::max();

for (std::size_t i = 0; i < _fileFilters.size(); ++i)
{
if (string::iequals(ext, _fileFilters[i].extension))
{
_dialog->SetFilterIndex(i);
return;
}

if (_fileFilters[i].extension == WILDCARD_EXTENSION)
{
wildCardIndex = i;
}
}

// Select the * extension if there's no better match
if (wildCardIndex < _fileFilters.size())
{
_dialog->SetFilterIndex(wildCardIndex);
}
}

Expand Down
3 changes: 3 additions & 0 deletions libs/wxutil/FileChooser.h
Expand Up @@ -32,6 +32,7 @@ class FileChooser :
{
std::string caption; // "Doom 3 Map (*.map)"
std::string filter; // "*.map"
std::string extension; // "map"
std::string mapFormatName;
};

Expand Down Expand Up @@ -107,6 +108,8 @@ class FileChooser :
private:
static long getStyle(bool open);

void selectFilterIndexFromFilename(const std::string& filename);

void construct(); // shared constructor stuff
};

Expand Down

0 comments on commit ced0c50

Please sign in to comment.