ImportDialog.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ImportDialog.h"
  7. #include "Spreadsheet.h"
  8. #include <AK/JsonParser.h>
  9. #include <AK/LexicalPath.h>
  10. #include <Applications/Spreadsheet/CSVImportGML.h>
  11. #include <Applications/Spreadsheet/FormatSelectionPageGML.h>
  12. #include <LibGUI/Application.h>
  13. #include <LibGUI/CheckBox.h>
  14. #include <LibGUI/ComboBox.h>
  15. #include <LibGUI/ItemListModel.h>
  16. #include <LibGUI/RadioButton.h>
  17. #include <LibGUI/StackWidget.h>
  18. #include <LibGUI/TableView.h>
  19. #include <LibGUI/TextBox.h>
  20. #include <LibGUI/Window.h>
  21. #include <LibGUI/Wizards/WizardDialog.h>
  22. #include <LibGUI/Wizards/WizardPage.h>
  23. namespace Spreadsheet {
  24. CSVImportDialogPage::CSVImportDialogPage(StringView csv)
  25. : m_csv(csv)
  26. {
  27. m_page = GUI::WizardPage::construct(
  28. "CSV Import Options",
  29. "Please select the options for the csv file you wish to import");
  30. m_page->body_widget().load_from_gml(csv_import_gml).release_value_but_fixme_should_propagate_errors();
  31. m_page->set_is_final_page(true);
  32. m_delimiter_comma_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_comma_radio");
  33. m_delimiter_semicolon_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_semicolon_radio");
  34. m_delimiter_tab_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_tab_radio");
  35. m_delimiter_space_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_space_radio");
  36. m_delimiter_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_other_radio");
  37. m_delimiter_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("delimiter_other_text_box");
  38. m_quote_single_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_single_radio");
  39. m_quote_double_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_double_radio");
  40. m_quote_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_other_radio");
  41. m_quote_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("quote_other_text_box");
  42. m_quote_escape_combo_box = m_page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("quote_escape_combo_box");
  43. m_read_header_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("read_header_check_box");
  44. m_trim_leading_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_leading_field_spaces_check_box");
  45. m_trim_trailing_field_spaces_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("trim_trailing_field_spaces_check_box");
  46. m_data_preview_table_view = m_page->body_widget().find_descendant_of_type_named<GUI::TableView>("data_preview_table_view");
  47. m_data_preview_error_label = m_page->body_widget().find_descendant_of_type_named<GUI::Label>("data_preview_error_label");
  48. m_data_preview_widget = m_page->body_widget().find_descendant_of_type_named<GUI::StackWidget>("data_preview_widget");
  49. m_quote_escape_combo_box->set_model(GUI::ItemListModel<DeprecatedString>::create(m_quote_escape_items));
  50. // By default, use commas, double quotes with repeat, and disable headers.
  51. m_delimiter_comma_radio->set_checked(true);
  52. m_quote_double_radio->set_checked(true);
  53. m_quote_escape_combo_box->set_selected_index(0); // Repeat
  54. m_delimiter_comma_radio->on_checked = [&](auto) { update_preview(); };
  55. m_delimiter_semicolon_radio->on_checked = [&](auto) { update_preview(); };
  56. m_delimiter_tab_radio->on_checked = [&](auto) { update_preview(); };
  57. m_delimiter_space_radio->on_checked = [&](auto) { update_preview(); };
  58. m_delimiter_other_radio->on_checked = [&](auto) { update_preview(); };
  59. m_delimiter_other_text_box->on_change = [&] {
  60. if (m_delimiter_other_radio->is_checked())
  61. update_preview();
  62. };
  63. m_quote_single_radio->on_checked = [&](auto) { update_preview(); };
  64. m_quote_double_radio->on_checked = [&](auto) { update_preview(); };
  65. m_quote_other_radio->on_checked = [&](auto) { update_preview(); };
  66. m_quote_other_text_box->on_change = [&] {
  67. if (m_quote_other_radio->is_checked())
  68. update_preview();
  69. };
  70. m_quote_escape_combo_box->on_change = [&](auto&, auto&) { update_preview(); };
  71. m_read_header_check_box->on_checked = [&](auto) { update_preview(); };
  72. m_trim_leading_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  73. m_trim_trailing_field_spaces_check_box->on_checked = [&](auto) { update_preview(); };
  74. update_preview();
  75. }
  76. auto CSVImportDialogPage::make_reader() -> Optional<Reader::XSV>
  77. {
  78. DeprecatedString delimiter;
  79. DeprecatedString quote;
  80. Reader::ParserTraits::QuoteEscape quote_escape;
  81. // Delimiter
  82. if (m_delimiter_other_radio->is_checked())
  83. delimiter = m_delimiter_other_text_box->text();
  84. else if (m_delimiter_comma_radio->is_checked())
  85. delimiter = ",";
  86. else if (m_delimiter_semicolon_radio->is_checked())
  87. delimiter = ";";
  88. else if (m_delimiter_tab_radio->is_checked())
  89. delimiter = "\t";
  90. else if (m_delimiter_space_radio->is_checked())
  91. delimiter = " ";
  92. else
  93. return {};
  94. // Quote separator
  95. if (m_quote_other_radio->is_checked())
  96. quote = m_quote_other_text_box->text();
  97. else if (m_quote_single_radio->is_checked())
  98. quote = "'";
  99. else if (m_quote_double_radio->is_checked())
  100. quote = "\"";
  101. else
  102. return {};
  103. // Quote escape
  104. auto index = m_quote_escape_combo_box->selected_index();
  105. if (index == 0)
  106. quote_escape = Reader::ParserTraits::Repeat;
  107. else if (index == 1)
  108. quote_escape = Reader::ParserTraits::Backslash;
  109. else
  110. return {};
  111. auto should_read_headers = m_read_header_check_box->is_checked();
  112. auto should_trim_leading = m_trim_leading_field_spaces_check_box->is_checked();
  113. auto should_trim_trailing = m_trim_trailing_field_spaces_check_box->is_checked();
  114. if (quote.is_empty() || delimiter.is_empty())
  115. return {};
  116. Reader::ParserTraits traits {
  117. move(delimiter),
  118. move(quote),
  119. quote_escape,
  120. };
  121. auto behaviors = Reader::default_behaviors() | Reader::ParserBehavior::Lenient;
  122. if (should_read_headers)
  123. behaviors = behaviors | Reader::ParserBehavior::ReadHeaders;
  124. if (should_trim_leading)
  125. behaviors = behaviors | Reader::ParserBehavior::TrimLeadingFieldSpaces;
  126. if (should_trim_trailing)
  127. behaviors = behaviors | Reader::ParserBehavior::TrimTrailingFieldSpaces;
  128. return Reader::XSV(m_csv, move(traits), behaviors);
  129. };
  130. void CSVImportDialogPage::update_preview()
  131. {
  132. m_previously_made_reader = make_reader();
  133. if (!m_previously_made_reader.has_value()) {
  134. m_data_preview_table_view->set_model(nullptr);
  135. m_data_preview_error_label->set_text("Could not read the given file"_string.release_value_but_fixme_should_propagate_errors());
  136. m_data_preview_widget->set_active_widget(m_data_preview_error_label);
  137. return;
  138. }
  139. auto& reader = *m_previously_made_reader;
  140. if (reader.has_error()) {
  141. m_data_preview_table_view->set_model(nullptr);
  142. m_data_preview_error_label->set_text(String::formatted("XSV parse error:\n{}", reader.error_string()).release_value_but_fixme_should_propagate_errors());
  143. m_data_preview_widget->set_active_widget(m_data_preview_error_label);
  144. return;
  145. }
  146. auto headers = reader.headers();
  147. m_data_preview_table_view->set_model(
  148. GUI::ItemListModel<Reader::XSV::Row, Reader::XSV, Vector<DeprecatedString>>::create(reader, headers, min(8ul, reader.size())));
  149. m_data_preview_widget->set_active_widget(m_data_preview_table_view);
  150. m_data_preview_table_view->update();
  151. }
  152. ErrorOr<Vector<NonnullRefPtr<Sheet>>, DeprecatedString> ImportDialog::make_and_run_for(GUI::Window& parent, StringView mime, String const& filename, Core::File& file, Workbook& workbook)
  153. {
  154. auto wizard = GUI::WizardDialog::construct(&parent);
  155. wizard->set_title("File Import Wizard");
  156. wizard->set_icon(GUI::Icon::default_icon("app-spreadsheet"sv).bitmap_for_size(16));
  157. auto import_xsv = [&]() -> ErrorOr<Vector<NonnullRefPtr<Sheet>>, DeprecatedString> {
  158. auto contents_or_error = file.read_until_eof();
  159. if (contents_or_error.is_error())
  160. return DeprecatedString::formatted("{}", contents_or_error.release_error());
  161. CSVImportDialogPage page { contents_or_error.release_value() };
  162. wizard->replace_page(page.page());
  163. auto result = wizard->exec();
  164. if (result == GUI::Dialog::ExecResult::OK) {
  165. auto& reader = page.reader();
  166. Vector<NonnullRefPtr<Sheet>> sheets;
  167. if (reader.has_value()) {
  168. reader->parse();
  169. if (reader.value().has_error())
  170. return DeprecatedString::formatted("CSV Import failed: {}", reader.value().error_string());
  171. auto sheet = Sheet::from_xsv(reader.value(), workbook);
  172. if (sheet)
  173. sheets.append(sheet.release_nonnull());
  174. }
  175. return sheets;
  176. }
  177. return DeprecatedString { "CSV Import was cancelled" };
  178. };
  179. auto import_worksheet = [&]() -> ErrorOr<Vector<NonnullRefPtr<Sheet>>, DeprecatedString> {
  180. auto contents_or_error = file.read_until_eof();
  181. if (contents_or_error.is_error())
  182. return DeprecatedString::formatted("{}", contents_or_error.release_error());
  183. auto json_value_option = JsonParser(contents_or_error.release_value()).parse();
  184. if (json_value_option.is_error())
  185. return DeprecatedString::formatted("Failed to parse {}", filename);
  186. auto& json_value = json_value_option.value();
  187. if (!json_value.is_array())
  188. return DeprecatedString::formatted("Did not find a spreadsheet in {}", filename);
  189. Vector<NonnullRefPtr<Sheet>> sheets;
  190. auto& json_array = json_value.as_array();
  191. json_array.for_each([&](auto& sheet_json) {
  192. if (!sheet_json.is_object())
  193. return IterationDecision::Continue;
  194. if (auto sheet = Sheet::from_json(sheet_json.as_object(), workbook))
  195. sheets.append(sheet.release_nonnull());
  196. return IterationDecision::Continue;
  197. });
  198. return sheets;
  199. };
  200. if (mime == "text/csv") {
  201. return import_xsv();
  202. } else if (mime == "application/x-sheets+json") {
  203. return import_worksheet();
  204. } else {
  205. auto page = GUI::WizardPage::construct(
  206. "Import File Format",
  207. DeprecatedString::formatted("Select the format you wish to import '{}' as", LexicalPath::basename(filename.to_deprecated_string())));
  208. page->on_next_page = [] { return nullptr; };
  209. page->body_widget().load_from_gml(select_format_page_gml).release_value_but_fixme_should_propagate_errors();
  210. auto format_combo_box = page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("select_format_page_format_combo_box");
  211. Vector<DeprecatedString> supported_formats {
  212. "CSV (text/csv)",
  213. "Spreadsheet Worksheet",
  214. };
  215. format_combo_box->set_model(GUI::ItemListModel<DeprecatedString>::create(supported_formats));
  216. wizard->push_page(page);
  217. if (wizard->exec() != GUI::Dialog::ExecResult::OK)
  218. return DeprecatedString { "Import was cancelled" };
  219. if (format_combo_box->selected_index() == 0)
  220. return import_xsv();
  221. if (format_combo_box->selected_index() == 1)
  222. return import_worksheet();
  223. VERIFY_NOT_REACHED();
  224. }
  225. }
  226. };