Launcher.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. * Copyright (c) 2020, Nicholas Hollett <niax@niax.co.uk>, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Launcher.h"
  27. #include <AK/Function.h>
  28. #include <AK/JsonObject.h>
  29. #include <AK/JsonObjectSerializer.h>
  30. #include <AK/JsonValue.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/StringBuilder.h>
  33. #include <LibCore/ConfigFile.h>
  34. #include <LibDesktop/AppFile.h>
  35. #include <serenity.h>
  36. #include <spawn.h>
  37. #include <stdio.h>
  38. #include <sys/stat.h>
  39. namespace LaunchServer {
  40. static Launcher* s_the;
  41. static bool spawn(String executable, String argument);
  42. String Handler::name_from_executable(const StringView& executable)
  43. {
  44. auto separator = executable.find_last_of('/');
  45. if (separator.has_value()) {
  46. auto start = separator.value() + 1;
  47. return executable.substring_view(start, executable.length() - start);
  48. }
  49. return executable;
  50. }
  51. void Handler::from_executable(Type handler_type, const String& executable)
  52. {
  53. this->handler_type = handler_type;
  54. this->name = name_from_executable(executable);
  55. this->executable = executable;
  56. }
  57. String Handler::to_details_str() const
  58. {
  59. StringBuilder builder;
  60. JsonObjectSerializer obj { builder };
  61. obj.add("executable", executable);
  62. obj.add("name", name);
  63. switch (handler_type) {
  64. case Type::Application:
  65. obj.add("type", "app");
  66. break;
  67. case Type::UserDefault:
  68. obj.add("type", "userdefault");
  69. break;
  70. case Type::UserPreferred:
  71. obj.add("type", "userpreferred");
  72. break;
  73. default:
  74. break;
  75. }
  76. obj.finish();
  77. return builder.build();
  78. }
  79. Launcher::Launcher()
  80. {
  81. ASSERT(s_the == nullptr);
  82. s_the = this;
  83. }
  84. Launcher& Launcher::the()
  85. {
  86. ASSERT(s_the);
  87. return *s_the;
  88. }
  89. void Launcher::load_handlers(const String& af_dir)
  90. {
  91. Desktop::AppFile::for_each([&](auto af) {
  92. auto app_name = af->name();
  93. auto app_executable = af->executable();
  94. HashTable<String> file_types;
  95. for (auto& file_type : af->launcher_file_types())
  96. file_types.set(file_type);
  97. HashTable<String> protocols;
  98. for (auto& protocol : af->launcher_protocols())
  99. protocols.set(protocol);
  100. m_handlers.set(app_executable, { Handler::Type::Default, app_name, app_executable, file_types, protocols });
  101. },
  102. af_dir);
  103. }
  104. void Launcher::load_config(const Core::ConfigFile& cfg)
  105. {
  106. for (auto key : cfg.keys("FileType")) {
  107. auto handler = cfg.read_entry("FileType", key).trim_whitespace();
  108. if (handler.is_empty())
  109. continue;
  110. m_file_handlers.set(key.to_lowercase(), handler);
  111. }
  112. for (auto key : cfg.keys("Protocol")) {
  113. auto handler = cfg.read_entry("Protocol", key).trim_whitespace();
  114. if (handler.is_empty())
  115. continue;
  116. m_protocol_handlers.set(key.to_lowercase(), handler);
  117. }
  118. }
  119. Vector<String> Launcher::handlers_for_url(const URL& url)
  120. {
  121. Vector<String> handlers;
  122. if (url.protocol() == "file") {
  123. for_each_handler_for_path(url.path(), [&](auto& handler) -> bool {
  124. handlers.append(handler.executable);
  125. return true;
  126. });
  127. } else {
  128. for_each_handler(url.protocol(), m_protocol_handlers, [&](const auto& handler) -> bool {
  129. if (handler.handler_type != Handler::Type::Default || handler.protocols.contains(url.protocol())) {
  130. handlers.append(handler.executable);
  131. return true;
  132. }
  133. return false;
  134. });
  135. }
  136. return handlers;
  137. }
  138. Vector<String> Launcher::handlers_with_details_for_url(const URL& url)
  139. {
  140. Vector<String> handlers;
  141. if (url.protocol() == "file") {
  142. for_each_handler_for_path(url.path(), [&](auto& handler) -> bool {
  143. handlers.append(handler.to_details_str());
  144. return true;
  145. });
  146. } else {
  147. for_each_handler(url.protocol(), m_protocol_handlers, [&](const auto& handler) -> bool {
  148. if (handler.handler_type != Handler::Type::Default || handler.protocols.contains(url.protocol())) {
  149. handlers.append(handler.to_details_str());
  150. return true;
  151. }
  152. return false;
  153. });
  154. }
  155. return handlers;
  156. }
  157. bool Launcher::open_url(const URL& url, const String& handler_name)
  158. {
  159. if (!handler_name.is_null())
  160. return open_with_handler_name(url, handler_name);
  161. if (url.protocol() == "file")
  162. return open_file_url(url);
  163. return open_with_user_preferences(m_protocol_handlers, url.protocol(), url.to_string());
  164. }
  165. bool Launcher::open_with_handler_name(const URL& url, const String& handler_name)
  166. {
  167. auto handler_optional = m_handlers.get(handler_name);
  168. if (!handler_optional.has_value())
  169. return false;
  170. auto& handler = handler_optional.value();
  171. String argument;
  172. if (url.protocol() == "file")
  173. argument = url.path();
  174. else
  175. argument = url.to_string();
  176. return spawn(handler.executable, argument);
  177. }
  178. bool spawn(String executable, String argument)
  179. {
  180. pid_t child_pid;
  181. const char* argv[] = { executable.characters(), argument.characters(), nullptr };
  182. if ((errno = posix_spawn(&child_pid, executable.characters(), nullptr, nullptr, const_cast<char**>(argv), environ))) {
  183. perror("posix_spawn");
  184. return false;
  185. } else {
  186. if (disown(child_pid) < 0)
  187. perror("disown");
  188. }
  189. return true;
  190. }
  191. Handler Launcher::get_handler_for_executable(Handler::Type handler_type, const String& executable) const
  192. {
  193. Handler handler;
  194. auto existing_handler = m_handlers.get(executable);
  195. if (existing_handler.has_value()) {
  196. handler = existing_handler.value();
  197. handler.handler_type = handler_type;
  198. } else {
  199. handler.from_executable(handler_type, executable);
  200. }
  201. return handler;
  202. }
  203. bool Launcher::open_with_user_preferences(const HashMap<String, String>& user_preferences, const String key, const String argument, const String default_program)
  204. {
  205. auto program_path = user_preferences.get(key);
  206. if (program_path.has_value())
  207. return spawn(program_path.value(), argument);
  208. // There wasn't a handler for this, so try the fallback instead
  209. program_path = user_preferences.get("*");
  210. if (program_path.has_value())
  211. return spawn(program_path.value(), argument);
  212. // Absolute worst case, try the provided default program, if any
  213. if (!default_program.is_empty())
  214. return spawn(default_program, argument);
  215. return false;
  216. }
  217. void Launcher::for_each_handler(const String& key, HashMap<String, String>& user_preference, Function<bool(const Handler&)> f)
  218. {
  219. auto user_preferred = user_preference.get(key);
  220. if (user_preferred.has_value())
  221. f(get_handler_for_executable(Handler::Type::UserPreferred, user_preferred.value()));
  222. size_t counted = 0;
  223. for (auto& handler : m_handlers) {
  224. // Skip over the existing item in the list
  225. if (user_preferred.has_value() && user_preferred.value() == handler.value.executable)
  226. continue;
  227. if (f(handler.value))
  228. counted++;
  229. }
  230. auto user_default = user_preference.get("*");
  231. if (counted == 0 && user_default.has_value())
  232. f(get_handler_for_executable(Handler::Type::UserDefault, user_default.value()));
  233. }
  234. void Launcher::for_each_handler_for_path(const String& path, Function<bool(const Handler&)> f)
  235. {
  236. struct stat st;
  237. if (stat(path.characters(), &st) < 0) {
  238. perror("stat");
  239. return;
  240. }
  241. // TODO: Make directory opening configurable
  242. if (S_ISDIR(st.st_mode)) {
  243. f(get_handler_for_executable(Handler::Type::Default, "/bin/FileManager"));
  244. return;
  245. }
  246. if ((st.st_mode & S_IFMT) == S_IFREG && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
  247. f(get_handler_for_executable(Handler::Type::Application, path));
  248. auto extension = LexicalPath(path).extension().to_lowercase();
  249. for_each_handler(extension, m_file_handlers, [&](const auto& handler) -> bool {
  250. if (handler.handler_type != Handler::Type::Default || handler.file_types.contains(extension))
  251. return f(handler);
  252. return false;
  253. });
  254. }
  255. bool Launcher::open_file_url(const URL& url)
  256. {
  257. struct stat st;
  258. if (stat(url.path().characters(), &st) < 0) {
  259. perror("stat");
  260. return false;
  261. }
  262. // TODO: Make directory opening configurable
  263. if (S_ISDIR(st.st_mode))
  264. return spawn("/bin/FileManager", url.path());
  265. if ((st.st_mode & S_IFMT) == S_IFREG && st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
  266. return spawn(url.path(), {});
  267. auto extension_parts = url.path().to_lowercase().split('.');
  268. String extension = {};
  269. if (extension_parts.size() > 1)
  270. extension = extension_parts.last();
  271. return open_with_user_preferences(m_file_handlers, extension, url.path(), "/bin/TextEditor");
  272. }
  273. }