aboutsummaryrefslogtreecommitdiff
path: root/src/jin/main.cpp
blob: 13dcc205caa5ef37ee26949c51eba2fc5d689eac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "libjin-lua/je_lua_jin.h"
#include "libjin/jin.h"

#ifdef _WIN32 
    #include <Windows.h>
    #include <shlobj.h>
    #include <wchar.h>
#endif 

#define EXECUTABLE_DIR "./" 
#define DIALOG_TITLE   L"Open existing game"

using namespace std;
using namespace JinEngine::Filesystem;

static void load(const char* cwd)
{
    jin_log_info("Currrent working directory is %s", cwd);
    // Main thread lua state.
    lua_State* L = luax_newstate();
    luax_openlibs(L);
    JinEngine::Lua::open(L);
    JinEngine::Lua::boot(L, cwd);
    luax_close(L);
}

#ifdef _WIN32
// WChar to string.
std::string wstrtostr(const std::wstring &wstr)
{
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}
#endif

bool BrowseFolder(string& cwd)
{
#ifdef _WIN32
    IFileDialog* pfd = NULL;
    DWORD dwFlags;
    IShellItem* pItem = NULL;
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr)) return false;
    hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
        IID_IFileOpenDialog, reinterpret_cast<void**>(&pfd));
    if (FAILED(hr)) return false;
    pfd->SetTitle(DIALOG_TITLE);
    hr = pfd->GetOptions(&dwFlags);
    if (FAILED(hr)) return false;
    hr = pfd->SetOptions(dwFlags | FOS_PICKFOLDERS);
    if (FAILED(hr)) return false;
    hr = pfd->Show(NULL);
    if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
        return false;
    hr = pfd->GetResult(&pItem);
    if (FAILED(hr)) return false;
    LPWSTR filePath;
    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &filePath);
    if (FAILED(hr)) return false;
    cwd = wstrtostr(filePath);
    CoTaskMemFree(filePath);
    pfd->Release();
    pItem->Release();
    CoUninitialize();
    return true;
#endif
}

int main(int argc, char* args[])
{
    string cwd = EXECUTABLE_DIR;
#ifdef _WIN32
    if (argc > 1)
        cwd = args[1];
#endif
    else
    {
        if (!BrowseFolder(cwd))
            return 0;
    }
    if (!cwd.empty())
        load(cwd.c_str());

    return 0;
}