1// LAF Base Library
2// Copyright (c) 2018-2021 Igara Studio S.A.
3// Copyright (c) 2001-2016 David Capello
4//
5// This file is released under the terms of the MIT license.
6// Read LICENSE.txt for more information.
7
8#ifdef HAVE_CONFIG_H
9#include "config.h"
10#endif
11
12#include "base/exception.h"
13#include "base/fs.h"
14#include "base/launcher.h"
15#include "base/string.h"
16
17#include <cstdlib>
18
19#if LAF_WINDOWS
20#include <windows.h>
21#ifndef SEE_MASK_DEFAULT
22#define SEE_MASK_DEFAULT 0x00000000
23#endif
24
25static int win32_shell_execute(const wchar_t* verb, const wchar_t* file, const wchar_t* params)
26{
27 SHELLEXECUTEINFO sh;
28 ZeroMemory((LPVOID)&sh, sizeof(sh));
29 sh.cbSize = sizeof(sh);
30 sh.fMask = SEE_MASK_DEFAULT;
31 sh.lpVerb = verb;
32 sh.lpFile = file;
33 sh.lpParameters = params;
34 sh.nShow = SW_SHOWNORMAL;
35
36 if (!ShellExecuteEx(&sh)) {
37 int ret = GetLastError();
38#if 0
39 if (ret != 0) {
40 DWORD flags =
41 FORMAT_MESSAGE_ALLOCATE_BUFFER |
42 FORMAT_MESSAGE_FROM_SYSTEM |
43 FORMAT_MESSAGE_IGNORE_INSERTS;
44 LPSTR msgbuf;
45
46 if (FormatMessageA(flags, NULL, ret,
47 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
48 reinterpret_cast<LPSTR>(&msgbuf),
49 0, NULL)) {
50 ui::Alert::show("Problem<<Cannot open:<<%s<<%s||&Close", file, msgbuf);
51 LocalFree(msgbuf);
52
53 ret = 0;
54 }
55 }
56#endif
57 return ret;
58 }
59 else
60 return 0;
61}
62#endif // LAF_WINDOWS
63
64namespace base {
65namespace launcher {
66
67bool open_url(const std::string& url)
68{
69 return open_file(url);
70}
71
72bool open_file(const std::string& file)
73{
74 int ret = -1;
75
76#if LAF_WINDOWS
77
78 ret = win32_shell_execute(L"open",
79 base::from_utf8(file).c_str(), NULL);
80
81#elif HAVE_SYSTEM
82
83 #if __APPLE__
84 ret = std::system(("open \"" + file + "\"").c_str());
85 #else
86 ret = std::system(("setsid xdg-open \"" + file + "\"").c_str());
87 #endif
88
89#endif
90
91 return (ret == 0);
92}
93
94bool open_folder(const std::string& _file)
95{
96 std::string file = base::fix_path_separators(_file);
97
98#if LAF_WINDOWS
99
100 int ret;
101 if (base::is_directory(file)) {
102 ret = win32_shell_execute(NULL, L"explorer",
103 (L"/n,/e,\"" + base::from_utf8(file) + L"\"").c_str());
104 }
105 else {
106 ret = win32_shell_execute(NULL, L"explorer",
107 (L"/e,/select,\"" + base::from_utf8(file) + L"\"").c_str());
108 }
109 return (ret == 0);
110
111#elif HAVE_SYSTEM
112
113 #if __APPLE__
114
115 int ret;
116 if (base::is_directory(file))
117 ret = std::system(("open \"" + file + "\"").c_str());
118 else
119 ret = std::system(("open --reveal \"" + file + "\"").c_str());
120 return (ret == 0);
121
122 #else
123
124 if (!base::is_directory(file))
125 file = base::get_file_path(file);
126
127 int ret = std::system(("setsid xdg-open \"" + file + "\"").c_str());
128 return (ret == 0);
129
130 #endif
131
132#else // HAVE_SYSTEM
133
134 return false;
135
136#endif
137}
138
139} // namespace launcher
140} // namespace base
141