ExportDialog.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "ExportDialog.h"
  7. #include "Spreadsheet.h"
  8. #include "Workbook.h"
  9. #include <AK/JsonArray.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/String.h>
  12. #include <Applications/Spreadsheet/CSVExportGML.h>
  13. #include <LibCore/File.h>
  14. #include <LibCore/FileStream.h>
  15. #include <LibCore/StandardPaths.h>
  16. #include <LibGUI/Application.h>
  17. #include <LibGUI/CheckBox.h>
  18. #include <LibGUI/ComboBox.h>
  19. #include <LibGUI/ItemListModel.h>
  20. #include <LibGUI/RadioButton.h>
  21. #include <LibGUI/TextBox.h>
  22. #include <LibGUI/Wizards/WizardDialog.h>
  23. #include <LibGUI/Wizards/WizardPage.h>
  24. #include <string.h>
  25. #include <unistd.h>
  26. // This is defined in ImportDialog.cpp, we can't include it twice, since the generated symbol is exported.
  27. extern char const select_format_page_gml[];
  28. namespace Spreadsheet {
  29. CSVExportDialogPage::CSVExportDialogPage(Sheet const& sheet)
  30. : m_data(sheet.to_xsv())
  31. {
  32. m_headers.extend(m_data.take_first());
  33. auto temp_template = String::formatted("{}/spreadsheet-csv-export.{}.XXXXXX", Core::StandardPaths::tempfile_directory(), getpid());
  34. auto temp_path = ByteBuffer::create_uninitialized(temp_template.length() + 1).release_value_but_fixme_should_propagate_errors();
  35. auto buf = reinterpret_cast<char*>(temp_path.data());
  36. auto copy_ok = temp_template.copy_characters_to_buffer(buf, temp_path.size());
  37. VERIFY(copy_ok);
  38. int fd = mkstemp(buf);
  39. if (fd < 0) {
  40. perror("mkstemp");
  41. // Just let the operation fail cleanly later.
  42. } else {
  43. unlink(buf);
  44. m_temp_output_file_path = temp_path;
  45. }
  46. m_page = GUI::WizardPage::construct(
  47. "CSV Export Options",
  48. "Please select the options for the csv file you wish to export to");
  49. m_page->body_widget().load_from_gml(csv_export_gml);
  50. m_page->set_is_final_page(true);
  51. m_delimiter_comma_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_comma_radio");
  52. m_delimiter_semicolon_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_semicolon_radio");
  53. m_delimiter_tab_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_tab_radio");
  54. m_delimiter_space_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_space_radio");
  55. m_delimiter_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("delimiter_other_radio");
  56. m_delimiter_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("delimiter_other_text_box");
  57. m_quote_single_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_single_radio");
  58. m_quote_double_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_double_radio");
  59. m_quote_other_radio = m_page->body_widget().find_descendant_of_type_named<GUI::RadioButton>("quote_other_radio");
  60. m_quote_other_text_box = m_page->body_widget().find_descendant_of_type_named<GUI::TextBox>("quote_other_text_box");
  61. m_quote_escape_combo_box = m_page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("quote_escape_combo_box");
  62. m_export_header_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("export_header_check_box");
  63. m_quote_all_fields_check_box = m_page->body_widget().find_descendant_of_type_named<GUI::CheckBox>("quote_all_fields_check_box");
  64. m_data_preview_text_editor = m_page->body_widget().find_descendant_of_type_named<GUI::TextEditor>("data_preview_text_editor");
  65. m_data_preview_text_editor->set_should_hide_unnecessary_scrollbars(true);
  66. m_quote_escape_combo_box->set_model(GUI::ItemListModel<String>::create(m_quote_escape_items));
  67. // By default, use commas, double quotes with repeat, disable headers, and quote only the fields that require quoting.
  68. m_delimiter_comma_radio->set_checked(true);
  69. m_quote_double_radio->set_checked(true);
  70. m_quote_escape_combo_box->set_selected_index(0); // Repeat
  71. m_delimiter_comma_radio->on_checked = [&](auto) { update_preview(); };
  72. m_delimiter_semicolon_radio->on_checked = [&](auto) { update_preview(); };
  73. m_delimiter_tab_radio->on_checked = [&](auto) { update_preview(); };
  74. m_delimiter_space_radio->on_checked = [&](auto) { update_preview(); };
  75. m_delimiter_other_radio->on_checked = [&](auto) { update_preview(); };
  76. m_delimiter_other_text_box->on_change = [&] {
  77. if (m_delimiter_other_radio->is_checked())
  78. update_preview();
  79. };
  80. m_quote_single_radio->on_checked = [&](auto) { update_preview(); };
  81. m_quote_double_radio->on_checked = [&](auto) { update_preview(); };
  82. m_quote_other_radio->on_checked = [&](auto) { update_preview(); };
  83. m_quote_other_text_box->on_change = [&] {
  84. if (m_quote_other_radio->is_checked())
  85. update_preview();
  86. };
  87. m_quote_escape_combo_box->on_change = [&](auto&, auto&) { update_preview(); };
  88. m_export_header_check_box->on_checked = [&](auto) { update_preview(); };
  89. m_quote_all_fields_check_box->on_checked = [&](auto) { update_preview(); };
  90. update_preview();
  91. }
  92. auto CSVExportDialogPage::make_writer() -> Optional<XSV>
  93. {
  94. String delimiter;
  95. String quote;
  96. Writer::WriterTraits::QuoteEscape quote_escape;
  97. // Delimiter
  98. if (m_delimiter_other_radio->is_checked())
  99. delimiter = m_delimiter_other_text_box->text();
  100. else if (m_delimiter_comma_radio->is_checked())
  101. delimiter = ",";
  102. else if (m_delimiter_semicolon_radio->is_checked())
  103. delimiter = ";";
  104. else if (m_delimiter_tab_radio->is_checked())
  105. delimiter = "\t";
  106. else if (m_delimiter_space_radio->is_checked())
  107. delimiter = " ";
  108. else
  109. return {};
  110. // Quote separator
  111. if (m_quote_other_radio->is_checked())
  112. quote = m_quote_other_text_box->text();
  113. else if (m_quote_single_radio->is_checked())
  114. quote = "'";
  115. else if (m_quote_double_radio->is_checked())
  116. quote = "\"";
  117. else
  118. return {};
  119. // Quote escape
  120. auto index = m_quote_escape_combo_box->selected_index();
  121. if (index == 0)
  122. quote_escape = Writer::WriterTraits::Repeat;
  123. else if (index == 1)
  124. quote_escape = Writer::WriterTraits::Backslash;
  125. else
  126. return {};
  127. auto should_export_headers = m_export_header_check_box->is_checked();
  128. auto should_quote_all_fields = m_quote_all_fields_check_box->is_checked();
  129. if (quote.is_empty() || delimiter.is_empty())
  130. return {};
  131. Writer::WriterTraits traits {
  132. move(delimiter),
  133. move(quote),
  134. quote_escape,
  135. };
  136. auto behaviors = Writer::default_behaviors();
  137. Vector<String> empty_headers;
  138. auto* headers = &empty_headers;
  139. if (should_export_headers) {
  140. behaviors = behaviors | Writer::WriterBehavior::WriteHeaders;
  141. headers = &m_headers;
  142. }
  143. if (should_quote_all_fields)
  144. behaviors = behaviors | Writer::WriterBehavior::QuoteAll;
  145. // Note that the stream is used only by the ctor.
  146. auto stream = Core::OutputFileStream::open(m_temp_output_file_path);
  147. if (stream.is_error()) {
  148. dbgln("Cannot open {} for writing: {}", m_temp_output_file_path, stream.error());
  149. return {};
  150. }
  151. XSV writer(stream.value(), m_data, traits, *headers, behaviors);
  152. if (stream.value().has_any_error()) {
  153. dbgln("Write error when making preview");
  154. return {};
  155. }
  156. return writer;
  157. }
  158. void CSVExportDialogPage::update_preview()
  159. {
  160. m_previously_made_writer = make_writer();
  161. if (!m_previously_made_writer.has_value()) {
  162. fail:;
  163. m_data_preview_text_editor->set_text({});
  164. return;
  165. }
  166. auto file_or_error = Core::File::open(
  167. m_temp_output_file_path,
  168. Core::OpenMode::ReadOnly);
  169. if (file_or_error.is_error())
  170. goto fail;
  171. auto& file = *file_or_error.value();
  172. StringBuilder builder;
  173. size_t line = 0;
  174. while (file.can_read_line()) {
  175. if (++line == 8)
  176. break;
  177. builder.append(file.read_line());
  178. builder.append('\n');
  179. }
  180. m_data_preview_text_editor->set_text(builder.string_view());
  181. m_data_preview_text_editor->update();
  182. }
  183. Result<void, String> CSVExportDialogPage::move_into(String const& target)
  184. {
  185. auto& source = m_temp_output_file_path;
  186. // First, try rename().
  187. auto rc = rename(source.characters(), target.characters());
  188. if (rc == 0)
  189. return {};
  190. auto saved_errno = errno;
  191. if (saved_errno == EXDEV) {
  192. // Can't do that, copy it instead.
  193. auto result = Core::File::copy_file_or_directory(
  194. target, source,
  195. Core::File::RecursionMode::Disallowed,
  196. Core::File::LinkMode::Disallowed,
  197. Core::File::AddDuplicateFileMarker::No);
  198. if (result.is_error())
  199. return String::formatted("{}", static_cast<Error const&>(result.error()));
  200. return {};
  201. }
  202. perror("rename");
  203. return String { strerror(saved_errno) };
  204. }
  205. Result<void, String> ExportDialog::make_and_run_for(StringView mime, Core::File& file, Workbook& workbook)
  206. {
  207. auto wizard = GUI::WizardDialog::construct(GUI::Application::the()->active_window());
  208. wizard->set_title("File Export Wizard");
  209. wizard->set_icon(GUI::Icon::default_icon("app-spreadsheet").bitmap_for_size(16));
  210. auto export_xsv = [&]() -> Result<void, String> {
  211. // FIXME: Prompt for the user to select a specific sheet to export
  212. // For now, export the first sheet (if available)
  213. if (!workbook.has_sheets())
  214. return String { "The workbook has no sheets to export!" };
  215. CSVExportDialogPage page { workbook.sheets().first() };
  216. wizard->replace_page(page.page());
  217. auto result = wizard->exec();
  218. if (result == GUI::Dialog::ExecResult::OK) {
  219. auto& writer = page.writer();
  220. if (!writer.has_value())
  221. return String { "CSV Export failed" };
  222. if (writer->has_error())
  223. return String::formatted("CSV Export failed: {}", writer->error_string());
  224. // No error, move the temp file to the expected location
  225. return page.move_into(file.filename());
  226. } else {
  227. return String { "CSV Export was cancelled" };
  228. }
  229. };
  230. auto export_worksheet = [&]() -> Result<void, String> {
  231. JsonArray array;
  232. for (auto& sheet : workbook.sheets())
  233. array.append(sheet.to_json());
  234. auto file_content = array.to_string();
  235. bool result = file.write(file_content);
  236. if (!result) {
  237. int error_number = errno;
  238. StringBuilder sb;
  239. sb.append("Unable to save file. Error: ");
  240. sb.append(strerror(error_number));
  241. return sb.to_string();
  242. }
  243. return {};
  244. };
  245. if (mime == "text/csv") {
  246. return export_xsv();
  247. } else if (mime == "text/plain" && file.filename().ends_with(".sheets")) {
  248. return export_worksheet();
  249. } else {
  250. auto page = GUI::WizardPage::construct(
  251. "Export File Format",
  252. String::formatted("Select the format you wish to export to '{}' as", LexicalPath::basename(file.filename())));
  253. page->on_next_page = [] { return nullptr; };
  254. page->body_widget().load_from_gml(select_format_page_gml);
  255. auto format_combo_box = page->body_widget().find_descendant_of_type_named<GUI::ComboBox>("select_format_page_format_combo_box");
  256. Vector<String> supported_formats {
  257. "CSV (text/csv)",
  258. "Spreadsheet Worksheet",
  259. };
  260. format_combo_box->set_model(GUI::ItemListModel<String>::create(supported_formats));
  261. wizard->push_page(page);
  262. if (wizard->exec() != GUI::Dialog::ExecResult::OK)
  263. return String { "Export was cancelled" };
  264. if (format_combo_box->selected_index() == 0)
  265. return export_xsv();
  266. if (format_combo_box->selected_index() == 1)
  267. return export_worksheet();
  268. VERIFY_NOT_REACHED();
  269. }
  270. }
  271. };