Write.as GTK desktop app https://write.as/apps/desktop
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

395 lines
14 KiB

  1. /*
  2. Copyright © 2018 Write.as
  3. This file is part of the Write.as GTK desktop app.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. public class WriteAs.MainWindow : Gtk.ApplicationWindow {
  16. private Gtk.TextView canvas;
  17. private Gtk.HeaderBar header;
  18. private Gtk.ToggleButton darkmode_button;
  19. private static string data_dir = ".writeas";
  20. private int font_size = 12;
  21. private bool dark_mode = false;
  22. private string font = "Lora, 'Palatino Linotype',"
  23. + "'Book Antiqua', 'New York', 'DejaVu serif', serif";
  24. private string fontstyle = "serif";
  25. private bool text_changed = false;
  26. private bool is_initializing = true;
  27. construct {
  28. header = new Gtk.HeaderBar();
  29. header.title = "Write.as";
  30. construct_toolbar();
  31. build_keyboard_shortcuts();
  32. var scrolled = new Gtk.ScrolledWindow(null, null);
  33. canvas = new Gtk.SourceView();
  34. canvas.wrap_mode = Gtk.WrapMode.WORD_CHAR;
  35. scrolled.add(canvas);
  36. add(scrolled);
  37. size_allocate.connect((_) => {adjust_text_style();});
  38. canvas.event_after.connect((evt) => {
  39. // TODO This word count algorithm may be quite naive
  40. // and could do improvement.
  41. var word_count = canvas.buffer.text.split(" ").length;
  42. header.subtitle = ngettext("%i word","%i words",word_count).printf(word_count);
  43. text_changed = true;
  44. });
  45. Timeout.add_full(Priority.DEFAULT_IDLE, 100/*ms*/, () => {
  46. if (!text_changed) return Source.CONTINUE;
  47. var text = canvas.buffer.text;
  48. // This happens sometimes for some reason, but it's difficult to debug.
  49. if (text == "") return Source.CONTINUE;
  50. try {
  51. draft_file().replace_contents(text.data, null, false,
  52. FileCreateFlags.PRIVATE | FileCreateFlags.REPLACE_DESTINATION,
  53. null);
  54. text_changed = false;
  55. } catch (Error err) {/* We'll try again anyways. */}
  56. return Source.CONTINUE;
  57. });
  58. adjust_text_style(false);
  59. }
  60. public MainWindow(Gtk.Application app) {
  61. set_application(app);
  62. icon_name = "write-as";
  63. init_folder();
  64. try {
  65. open_file(draft_file());
  66. } catch (Error err) {canvas.buffer.text = err.message;}
  67. restore_styles();
  68. set_default_size(800, 600);
  69. is_initializing = false;
  70. }
  71. private static void init_folder() {
  72. var home = File.new_for_path(get_data_dir());
  73. try {
  74. home.make_directory();
  75. } catch (Error e) {
  76. stderr.printf("Create data dir: %s\n", e.message);
  77. }
  78. }
  79. private static string get_data_dir() {
  80. return Environment.get_home_dir() + "/" + data_dir;
  81. }
  82. private static File draft_file() {
  83. var home = File.new_for_path(get_data_dir());
  84. return home.get_child("draft.txt");
  85. }
  86. private static bool supports_dark_theme() {
  87. var theme = Gtk.Settings.get_default().gtk_theme_name;
  88. foreach (var datapath in Environment.get_system_data_dirs()) {
  89. var path = File.new_for_path(Path.build_filename(datapath, "themes", theme));
  90. if (path.get_child("gtk-dark.css").query_exists()) return true;
  91. try {
  92. var enumerator = path.enumerate_children("standard::*", 0);
  93. FileInfo info = null;
  94. while ((info = enumerator.next_file()) != null) {
  95. var fullpath = path.get_child(info.get_name()).get_child("gtk-dark.css");
  96. if (fullpath.query_exists()) return true;
  97. }
  98. } catch (Error err) {/* Might be missing something, but no biggy. */}
  99. }
  100. return false;
  101. }
  102. private void construct_toolbar() {
  103. header.show_close_button = true;
  104. set_titlebar(header);
  105. var publish_button = new Gtk.Button.from_icon_name("document-send",
  106. Gtk.IconSize.SMALL_TOOLBAR);
  107. publish_button.clicked.connect(() => {
  108. canvas.buffer.text += "\n\n" + publish();
  109. canvas.grab_focus();
  110. });
  111. header.pack_end(publish_button);
  112. darkmode_button = new Gtk.ToggleButton();
  113. darkmode_button.tooltip_text = _("Toggle dark theme");
  114. // NOTE the fallback icon is a bit of a meaning stretch, but it works.
  115. var icon_theme = Gtk.IconTheme.get_default();
  116. darkmode_button.image = new Gtk.Image.from_icon_name(
  117. icon_theme.has_icon("writeas-bright-dark") ?
  118. "writeas-bright-dark" : "weather-clear-night",
  119. Gtk.IconSize.SMALL_TOOLBAR);
  120. darkmode_button.draw_indicator = false;
  121. var settings = Gtk.Settings.get_default();
  122. darkmode_button.toggled.connect(() => {
  123. settings.gtk_application_prefer_dark_theme = darkmode_button.active;
  124. dark_mode = darkmode_button.active;
  125. if (!is_initializing) theme_save();
  126. canvas.grab_focus();
  127. });
  128. if (supports_dark_theme()) header.pack_end(darkmode_button);
  129. var fonts = new Gtk.MenuButton();
  130. fonts.tooltip_text = _("Change document font");
  131. fonts.image = new Gtk.Image.from_icon_name("font-x-generic", Gtk.IconSize.SMALL_TOOLBAR);
  132. fonts.popup = new Gtk.Menu();
  133. header.pack_start(fonts);
  134. build_fontoption(fonts.popup, _("Serif"), "serif", font);
  135. build_fontoption(fonts.popup, _("Sans-serif"), "sans",
  136. "'Open Sans', 'Segoe UI', Tahoma, Arial, sans-serif");
  137. build_fontoption(fonts.popup, _("Monospace"), "wrap", "Hack, consolas," +
  138. "Menlo-Regular, Menlo, Monaco, 'ubuntu mono', monospace");
  139. fonts.popup.show_all();
  140. }
  141. private unowned SList<Gtk.RadioMenuItem>? font_options = null;
  142. private void build_fontoption(Gtk.Menu menu,
  143. string label, string fontstyle, string families) {
  144. var option = new Gtk.RadioMenuItem.with_label(font_options, label);
  145. font_options = option.get_group();
  146. option.activate.connect(() => {
  147. this.font = families;
  148. this.fontstyle = fontstyle;
  149. adjust_text_style(!is_initializing);
  150. canvas.grab_focus();
  151. });
  152. var styles = option.get_style_context();
  153. var provider = new Gtk.CssProvider();
  154. try {
  155. provider.load_from_data("* {font: %s;}".printf(families));
  156. styles.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
  157. } catch (Error e) {
  158. warning(e.message);
  159. }
  160. menu.add(option);
  161. }
  162. public override void grab_focus() {
  163. canvas.grab_focus();
  164. }
  165. private KeyFile theme = new KeyFile();
  166. private void restore_styles() {
  167. try {
  168. loaded_theme = true;
  169. theme.load_from_file(get_data_dir() + "/prefs.ini", KeyFileFlags.NONE);
  170. dark_mode = theme.get_boolean("Theme", "darkmode");
  171. darkmode_button.set_active(dark_mode);
  172. Gtk.Settings.get_default().gtk_application_prefer_dark_theme = dark_mode;
  173. font_size = theme.get_integer("Theme", "fontsize");
  174. font = theme.get_string("Post", "font");
  175. fontstyle = theme.get_string("Post", "fontstyle");
  176. adjust_text_style(false);
  177. } catch (Error err) {/* No biggy... */}
  178. }
  179. private Gtk.CssProvider cur_styles = null;
  180. // So the theme isn't read before it's saved.
  181. private bool loaded_theme = false;
  182. private void adjust_text_style(bool save_theme = true) {
  183. try {
  184. if (cur_styles != null)
  185. Gtk.StyleContext.remove_provider_for_screen(Gdk.Screen.get_default(), cur_styles);
  186. var padding = canvas.get_allocated_width()*0.10;
  187. var css = ("GtkTextView {font: %s; font-size: %dpx; padding: 20px;" +
  188. " padding-left: %ipx; padding-right: %ipx;" +
  189. " -GtkWidget-cursor-color: #5ac4ee;}").printf(font, font_size,
  190. (int) padding, (int) padding);
  191. cur_styles = new Gtk.CssProvider();
  192. cur_styles.load_from_data(css);
  193. Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
  194. cur_styles, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
  195. if (save_theme) theme_save();
  196. } catch (Error e) {
  197. warning(e.message);
  198. }
  199. }
  200. private void theme_save() {
  201. if (!loaded_theme) return;
  202. theme.set_boolean("Theme", "darkmode", dark_mode);
  203. theme.set_integer("Theme", "fontsize", font_size);
  204. theme.set_string("Post", "font", font);
  205. theme.set_string("Post", "fontstyle", fontstyle);
  206. try {
  207. theme.save_to_file(get_data_dir() + "/prefs.ini");
  208. } catch (FileError err) {/* Oh well. */}
  209. }
  210. private string publish() {
  211. try {
  212. if (text_changed) {;
  213. draft_file().replace_contents(canvas.buffer.text.data, null, false,
  214. FileCreateFlags.PRIVATE | FileCreateFlags.REPLACE_DESTINATION,
  215. null);
  216. text_changed = false;
  217. }
  218. var cmd = "sh -c 'cat ~/" + data_dir + "/draft.txt | writeas --font %s'";
  219. cmd = cmd.printf(fontstyle);
  220. string stdout, stderr;
  221. int status;
  222. Process.spawn_command_line_sync(cmd,
  223. out stdout, out stderr, out status);
  224. // Open it in the browser
  225. if (status == 0) {
  226. var browser = AppInfo.get_default_for_uri_scheme("https");
  227. var urls = new List<string>();
  228. urls.append(stdout.strip());
  229. browser.launch_uris(urls, null);
  230. }
  231. return stderr.strip();
  232. } catch (Error err) {
  233. return err.message;
  234. }
  235. }
  236. /* --- */
  237. private void build_keyboard_shortcuts() {
  238. /* These operations are not exposed to the UI as buttons,
  239. as most people are very familiar with them and they are not the
  240. focus of this app. */
  241. var accels = new Gtk.AccelGroup();
  242. // App operations
  243. accels.connect(Gdk.Key.W, Gdk.ModifierType.CONTROL_MASK,
  244. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  245. (g,a,k,m) => quit());
  246. accels.connect(Gdk.Key.Q, Gdk.ModifierType.CONTROL_MASK,
  247. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  248. (g,a,k,m) => quit());
  249. // File operations
  250. accels.connect(Gdk.Key.S, Gdk.ModifierType.CONTROL_MASK,
  251. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  252. (g,a,k,m) => save_as());
  253. accels.connect(Gdk.Key.S,
  254. Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
  255. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  256. (g,a,k,m) => save_as());
  257. // Adjust text size
  258. accels.connect(Gdk.Key.minus, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  259. if (font_size < 3) {
  260. return false;
  261. }
  262. if (font_size <= 10) {
  263. font_size -= 1;
  264. } else {
  265. font_size -= 2;
  266. }
  267. adjust_text_style(true);
  268. return true;
  269. });
  270. accels.connect(Gdk.Key.equal, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  271. if (font_size < 10) {
  272. font_size += 1;
  273. } else {
  274. font_size += 2;
  275. }
  276. adjust_text_style(true);
  277. return true;
  278. });
  279. // Toggle theme with Ctrl+T
  280. accels.connect(Gdk.Key.T, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  281. darkmode_button.set_active(!darkmode_button.get_active());
  282. return true;
  283. });
  284. // Publish with Ctrl+Enter
  285. accels.connect(Gdk.Key.Return, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  286. canvas.buffer.text += "\n\n" + publish();
  287. return true;
  288. });
  289. add_accel_group(accels);
  290. }
  291. private bool save_as() {
  292. try {
  293. var file = prompt_file(Gtk.FileChooserAction.SAVE, _("_Save as"));
  294. file.replace_contents(canvas.buffer.text.data, null, false,
  295. FileCreateFlags.PRIVATE | FileCreateFlags.REPLACE_DESTINATION,
  296. null);
  297. } catch (Error e) {
  298. // It's fine...
  299. }
  300. return true;
  301. }
  302. private File prompt_file(Gtk.FileChooserAction mode, string action)
  303. throws UserCancellable {
  304. var file_chooser = new Gtk.FileChooserDialog(action, this, mode,
  305. _("_Cancel"), Gtk.ResponseType.CANCEL,
  306. action, Gtk.ResponseType.ACCEPT);
  307. file_chooser.select_multiple = false;
  308. var filter = new Gtk.FileFilter();
  309. filter.add_mime_type("text/plain");
  310. file_chooser.set_filter(filter);
  311. var resp = file_chooser.run();
  312. file_chooser.close();
  313. if (resp == Gtk.ResponseType.ACCEPT) {
  314. return file_chooser.get_file();
  315. } else {
  316. throw new UserCancellable.USER_CANCELLED("FileChooserDialog");
  317. }
  318. }
  319. public void open_file(File file) throws Error {
  320. uint8[] text;
  321. file.load_contents(null, out text, null);
  322. canvas.buffer.text = (string) text;
  323. }
  324. private bool quit() {
  325. this.close();
  326. return true;
  327. }
  328. }
  329. errordomain WriteAs.UserCancellable {USER_CANCELLED}