open_resource_dialog.vala 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2012-2026 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. namespace Crown
  6. {
  7. public class OpenResourceDialog : Gtk.FileChooserDialog
  8. {
  9. public Project _project;
  10. public string _resource_type;
  11. public signal void safer_response(int response_id, string? path);
  12. public OpenResourceDialog(string? title, Gtk.Window? parent, string resource_type, Project p)
  13. {
  14. if (title != null)
  15. this.title = title;
  16. if (parent != null)
  17. this.set_transient_for(parent);
  18. this.set_action(Gtk.FileChooserAction.OPEN);
  19. this.add_button("Cancel", Gtk.ResponseType.CANCEL);
  20. this.add_button("Open", Gtk.ResponseType.ACCEPT);
  21. try {
  22. this.set_current_folder_file(GLib.File.new_for_path(p.source_dir()));
  23. } catch (GLib.Error e) {
  24. loge(e.message);
  25. }
  26. this.set_modal(true);
  27. this.response.connect(on_response);
  28. Gtk.FileFilter ff = new Gtk.FileFilter();
  29. ff.set_filter_name("%s (*.%s)".printf(resource_type, resource_type));
  30. ff.add_pattern("*.%s".printf(resource_type));
  31. this.add_filter(ff);
  32. _project = p;
  33. _resource_type = resource_type;
  34. }
  35. public void on_response(int response_id)
  36. {
  37. string? path = this.get_file().get_path();
  38. if (response_id == Gtk.ResponseType.ACCEPT && path != null) {
  39. if (!path.has_suffix("." + _resource_type))
  40. path += "." + _resource_type;
  41. // If the path is outside the source dir, show a warning
  42. // and point the file chooser back to the source dir.
  43. if (!_project.path_is_within_source_dir(path)) {
  44. Gtk.MessageDialog md = new Gtk.MessageDialog(this
  45. , Gtk.DialogFlags.MODAL
  46. , Gtk.MessageType.WARNING
  47. , Gtk.ButtonsType.OK
  48. , "The file must be within the source directory."
  49. );
  50. md.set_default_response(Gtk.ResponseType.OK);
  51. md.response.connect(() => {
  52. try {
  53. this.set_current_folder_file(GLib.File.new_for_path(_project.source_dir()));
  54. } catch (GLib.Error e) {
  55. loge(e.message);
  56. }
  57. md.destroy();
  58. });
  59. md.show_all();
  60. return;
  61. }
  62. }
  63. this.safer_response(response_id, path);
  64. }
  65. }
  66. } /* namespace Crown */