aboutsummaryrefslogtreecommitdiff
path: root/src/jin/main.cpp
blob: 2f0f9b31c9fcd41c8a1642620f56f4cfb6fa2710 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "lua/luax.h"
#include "lua/jin.h"
#include "libjin/jin.h"

#ifdef _WIN32 
    #include <Windows.h>
    #include <SDL2/SDL_Main.h>
    #include <direct.h>
    #include <shlobj.h>
    #include <wchar.h>
#endif 

#define EXECUTABLE_DIR "./" 

using namespace std;
using namespace JinEngine::Filesystem;
using namespace JinEngine::Lua;

// Load game under cwd.
static void load(const char* cwd)
{

    // Global lua runtime.
    lua_State* L = luax_newstate();

    // Open lua standard module.
    luax_openlibs(L);
    // Open jin module.
    luaopen_jin(L);
    // Set current working directory.
    luax_newtable(L);
    luax_setfieldstring(L, "cwd", cwd);
    luax_setfield(L, -2, "args");
    // Clear lua stack.
    luax_clearstack(L);

    // Boot jin and run it.
    boot(L);

    // Close lua lib.
    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 

std::string BrowseFolder()
{
    string path = EXECUTABLE_DIR;
#ifdef _WIN32
    IFileDialog *pfd = NULL;
    DWORD dwFlags;
    IShellItem *pShellItem = NULL;
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr)) goto End;
    hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
        IID_IFileOpenDialog, reinterpret_cast<void**>(&pfd));
    if (FAILED(hr)) goto End;
    hr = pfd->GetOptions(&dwFlags);
    if (FAILED(hr)) goto End; 
    hr = pfd->SetOptions(dwFlags | FOS_PICKFOLDERS);
    if (FAILED(hr)) goto End;
    hr = pfd->Show(NULL);
    if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))
        goto End;
    hr = pfd->GetResult(&pShellItem);
    if (FAILED(hr)) goto End;
    LPWSTR filePath;
    hr = pShellItem->GetDisplayName(SIGDN_FILESYSPATH, &filePath);
    if (FAILED(hr))
    {
        goto End;
    }
    path = wstrtostr(filePath);
    CoTaskMemFree(filePath);
#endif
End:
    return path;
}

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

    return 0;
}