ImportDialog.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  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 "ImportDialog.h"
  27. #include "Spreadsheet.h"
  28. #include <AK/JsonArray.h>
  29. #include <AK/JsonObject.h>
  30. #include <AK/JsonParser.h>
  31. #include <AK/LexicalPath.h>
  32. #include <Applications/Spreadsheet/CSVImportGML.h>
  33. #include <Applications/Spreadsheet/FormatSelectionPageGML.h>
  34. #include <LibCore/File.h>
  35. #include <LibGUI/Application.h>
  36. #include <LibGUI/CheckBox.h>
  37. #include <LibGUI/ComboBox.h>
  38. #include <LibGUI/ItemListModel.h>
  39. #include <LibGUI/RadioButton.h>
  40. #include <LibGUI/TableView.h>
  41. #include <LibGUI/TextBox.h>
  42. #include <LibGUI/Wizards/AbstractWizardPage.h>
  43. #include <LibGUI/Wizards/WizardDialog.h>
  44. #include <LibGUI/Wizards/WizardPage.h>
  45. namespace Spreadsheet {
  46. CSVImportDialogPage::CSVImportDialogPage(StringView csv)
  47. : m_csv(csv)
  48. {
  49. m_page = GUI::WizardPage::construct(
  50. "CSV Import Options",
  51. "Please select the options for the csv file you wish to import");
  52. m_page->body_widget().load_from_gml(csv_import_gml);
  53. m_page->set_is_final_page(true);
  54. m_delimiter_comma_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_comma_radio");
  55. m_delimiter_semicolon_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_semicolon_radio");
  56. m_delimiter_tab_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_tab_radio");
  57. m_delimiter_space_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_space_radio");
  58. m_delimiter_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_other_radio");
  59. m_delimiter_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("delimiter_other_text_box");
  60. m_quote_single_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_single_radio");
  61. m_quote_double_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_double_radio");
  62. m_quote_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_other_radio");
  63. m_quote_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("quote_other_text_box");
  64. m_quote_escape_combo_box = m_page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("quote_escape_combo_box");
  65. m_read_header_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("read_header_check_box");
  66. m_trim_leading_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_leading_field_spaces_check_box");
  67. m_trim_trailing_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_trailing_field_spaces_check_box");
  68. m_data_preview_table_view = m_page->body_widget().find_descendant_of_type_named<GUI::TableView>("data_preview_table_view");
  69. Vector<String> quote_escape_items {
  70. // Note: Keep in sync with Reader::ParserTraits::QuoteEscape.
  71. "Repeat",
  72. "Backslash",
  73. };
  74. m_quote_escape_combo_box->set_model(GUI::ItemListModel<String>::create(quote_escape_items));
  75. // By default, use commas, double quotes with repeat, and disable headers.
  76. m_delimiter_comma_radio->set_checked(true);
  77. m_quote_double_radio->set_checked(true);
  78. m_quote_escape_combo_box->set_selected_index(0); // Repeat
  79. m_delimiter_comma_radio->on_checked = [&](auto) { update_preview(); };
  80. m_delimiter_semicolon_radio->on_checked = [&](auto) { update_preview(); };
  81. m_delimiter_tab_radio->on_checked = [&](auto) { update_preview(); };
  82. m_delimiter_space_radio->on_checked = [&](auto) { update_preview(); };
  83. m_delimiter_other_radio->on_checked = [&](auto) { update_preview(); };
  84. m_delimiter_other_text_box->on_change = [&](auto&) {
  85. if (m_delimiter_other_radio->is_checked())
  86. update_preview();
  87. };
  88. m_quote_single_radio->on_checked = [&](auto) { update_preview(); };
  89. m_quote_double_radio->on_checked = [&](auto) { update_preview(); };
  90. m_quote_other_radio->on_checked = [&](auto) { update_preview(); };
  91. m_quote_other_text_box->on_change = [&](auto&) {
  92. if (m_quote_other_radio->is_checked())
  93. update_preview();
  94. };
  95. m_quote_escape_combo_box->on_change = [&](auto&) { update_preview(); };
  96. m_read_header_check_box->on_checked = [&](auto) { update_preview(); };
  97. m_trim_leading_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  98. m_trim_trailing_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  99. update_preview();
  100. }
  101. auto CSVImportDialogPage::make_reader() -> Optional<Reader::XSV>
  102. {
  103. String delimiter;
  104. String quote;
  105. Reader::ParserTraits::QuoteEscape quote_escape;
  106. // Delimiter
  107. if (m_delimiter_other_radio->is_checked())
  108. delimiter = m_delimiter_other_text_box->text();
  109. else if (m_delimiter_comma_radio->is_checked())
  110. delimiter = ",";
  111. else if (m_delimiter_semicolon_radio->is_checked())
  112. delimiter = ";";
  113. else if (m_delimiter_tab_radio->is_checked())
  114. delimiter = "\t";
  115. else if (m_delimiter_space_radio->is_checked())
  116. delimiter = " ";
  117. else
  118. return {};
  119. // Quote separator
  120. if (m_quote_other_radio->is_checked())
  121. quote = m_quote_other_text_box->text();
  122. else if (m_quote_single_radio->is_checked())
  123. quote = "'";
  124. else if (m_quote_double_radio->is_checked())
  125. quote = "\"";
  126. else
  127. return {};
  128. // Quote escape
  129. auto index = m_quote_escape_combo_box->selected_index();
  130. if (index == 0)
  131. quote_escape = Reader::ParserTraits::Repeat;
  132. else if (index == 1)
  133. quote_escape = Reader::ParserTraits::Backslash;
  134. else
  135. return {};
  136. auto should_read_headers = m_read_header_check_box->is_checked();
  137. auto should_trim_leading = m_trim_leading_field_spaces_check_box->is_checked();
  138. auto should_trim_trailing = m_trim_trailing_field_spaces_check_box->is_checked();
  139. if (quote.is_empty() || delimiter.is_empty())
  140. return {};
  141. Reader::ParserTraits traits {
  142. move(delimiter),
  143. move(quote),
  144. quote_escape,
  145. };
  146. auto behaviours = Reader::default_behaviours();
  147. if (should_read_headers)
  148. behaviours = behaviours | Reader::ParserBehaviour::ReadHeaders;
  149. if (should_trim_leading)
  150. behaviours = behaviours | Reader::ParserBehaviour::TrimLeadingFieldSpaces;
  151. if (should_trim_trailing)
  152. behaviours = behaviours | Reader::ParserBehaviour::TrimTrailingFieldSpaces;
  153. return Reader::XSV(m_csv, traits, behaviours);
  154. };
  155. void CSVImportDialogPage::update_preview()
  156. {
  157. m_previously_made_reader = make_reader();
  158. if (!m_previously_made_reader.has_value()) {
  159. m_data_preview_table_view->set_model(nullptr);
  160. return;
  161. }
  162. auto& reader = *m_previously_made_reader;
  163. auto headers = reader.headers();
  164. m_data_preview_table_view->set_model(
  165. GUI::ItemListModel<Reader::XSV::Row, Reader::XSV, Vector<String>>::create(reader, headers, min(8ul, reader.size())));
  166. m_data_preview_table_view->update();
  167. }
  168. Result<NonnullRefPtrVector<Sheet>, String> ImportDialog::make_and_run_for(StringView mime, Core::File& file, Workbook& workbook)
  169. {
  170. auto wizard = GUI::WizardDialog::construct(GUI::Application::the()->active_window());
  171. wizard->set_title("File Import Wizard");
  172. wizard->set_icon(GUI::Icon::default_icon("app-spreadsheet").bitmap_for_size(16));
  173. auto import_xsv = [&]() -> Result<NonnullRefPtrVector<Sheet>, String> {
  174. auto contents = file.read_all();
  175. CSVImportDialogPage page { contents };
  176. wizard->replace_page(page.page());
  177. auto result = wizard->exec();
  178. if (result == GUI::Dialog::ExecResult::ExecOK) {
  179. auto& reader = page.reader();
  180. NonnullRefPtrVector<Sheet> sheets;
  181. if (reader.has_value()) {
  182. auto sheet = Sheet::from_xsv(reader.value(), workbook);
  183. if (sheet)
  184. sheets.append(sheet.release_nonnull());
  185. }
  186. return sheets;
  187. } else {
  188. return String { "CSV Import was cancelled" };
  189. }
  190. };
  191. auto import_worksheet = [&]() -> Result<NonnullRefPtrVector<Sheet>, String> {
  192. auto json_value_option = JsonParser(file.read_all()).parse();
  193. if (!json_value_option.has_value()) {
  194. StringBuilder sb;
  195. sb.append("Failed to parse ");
  196. sb.append(file.filename());
  197. return sb.to_string();
  198. }
  199. auto& json_value = json_value_option.value();
  200. if (!json_value.is_array()) {
  201. StringBuilder sb;
  202. sb.append("Did not find a spreadsheet in ");
  203. sb.append(file.filename());
  204. return sb.to_string();
  205. }
  206. NonnullRefPtrVector<Sheet> sheets;
  207. auto& json_array = json_value.as_array();
  208. json_array.for_each([&](auto& sheet_json) {
  209. if (!sheet_json.is_object())
  210. return IterationDecision::Continue;
  211. if (auto sheet = Sheet::from_json(sheet_json.as_object(), workbook))
  212. sheets.append(sheet.release_nonnull());
  213. return IterationDecision::Continue;
  214. });
  215. return sheets;
  216. };
  217. if (mime == "text/csv") {
  218. return import_xsv();
  219. } else if (mime == "text/plain" && file.filename().ends_with(".sheets")) {
  220. return import_worksheet();
  221. } else {
  222. auto page = GUI::WizardPage::construct(
  223. "Import File Format",
  224. String::formatted("Select the format you wish to import '{}' as", LexicalPath { file.filename() }.basename()));
  225. page->on_next_page = [] { return nullptr; };
  226. page->body_widget().load_from_gml(select_format_page_gml);
  227. auto format_combo_box = page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("select_format_page_format_combo_box");
  228. Vector<String> supported_formats {
  229. "CSV (text/csv)",
  230. "Spreadsheet Worksheet",
  231. };
  232. format_combo_box->set_model(GUI::ItemListModel<String>::create(supported_formats));
  233. wizard->push_page(page);
  234. if (wizard->exec() != GUI::Dialog::ExecResult::ExecOK)
  235. return String { "Import was cancelled" };
  236. if (format_combo_box->selected_index() == 0)
  237. return import_xsv();
  238. if (format_combo_box->selected_index() == 1)
  239. return import_worksheet();
  240. VERIFY_NOT_REACHED();
  241. }
  242. }
  243. };