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.
 
 
 

380 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.TextView();
  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 void construct_toolbar() {
  87. header.show_close_button = true;
  88. set_titlebar(header);
  89. var publish_button = new Gtk.Button.from_icon_name("document-send",
  90. Gtk.IconSize.SMALL_TOOLBAR);
  91. publish_button.clicked.connect(() => {
  92. canvas.buffer.text += "\n\n" + publish();
  93. });
  94. header.pack_end(publish_button);
  95. darkmode_button = new Gtk.ToggleButton();
  96. darkmode_button.tooltip_text = _("Toggle dark theme");
  97. // NOTE the fallback icon is a bit of a meaning stretch, but it works.
  98. var icon_theme = Gtk.IconTheme.get_default();
  99. darkmode_button.image = new Gtk.Image.from_icon_name(
  100. icon_theme.has_icon("writeas-bright-dark") ?
  101. "writeas-bright-dark" : "weather-clear-night",
  102. Gtk.IconSize.SMALL_TOOLBAR);
  103. darkmode_button.draw_indicator = false;
  104. var settings = Gtk.Settings.get_default();
  105. darkmode_button.toggled.connect(() => {
  106. settings.gtk_application_prefer_dark_theme = darkmode_button.active;
  107. dark_mode = darkmode_button.active;
  108. adjust_text_style(!is_initializing);
  109. });
  110. header.pack_end(darkmode_button);
  111. var fonts = new Gtk.MenuButton();
  112. fonts.tooltip_text = _("Change document font");
  113. fonts.image = new Gtk.Image.from_icon_name("font-x-generic", Gtk.IconSize.SMALL_TOOLBAR);
  114. fonts.popup = new Gtk.Menu();
  115. header.pack_start(fonts);
  116. build_fontoption(fonts.popup, _("Serif"), "serif", font);
  117. build_fontoption(fonts.popup, _("Sans-serif"), "sans",
  118. "'Open Sans', 'Segoe UI', Tahoma, Arial, sans-serif");
  119. build_fontoption(fonts.popup, _("Monospace"), "wrap", "Hack, consolas," +
  120. "Menlo-Regular, Menlo, Monaco, 'ubuntu mono', monospace");
  121. fonts.popup.show_all();
  122. }
  123. private unowned SList<Gtk.RadioMenuItem>? font_options = null;
  124. private void build_fontoption(Gtk.Menu menu,
  125. string label, string fontstyle, string families) {
  126. var option = new Gtk.RadioMenuItem.with_label(font_options, label);
  127. font_options = option.get_group();
  128. option.activate.connect(() => {
  129. this.font = families;
  130. this.fontstyle = fontstyle;
  131. adjust_text_style(!is_initializing);
  132. });
  133. var styles = option.get_style_context();
  134. var provider = new Gtk.CssProvider();
  135. try {
  136. provider.load_from_data("* {font: %s;}".printf(families));
  137. styles.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
  138. } catch (Error e) {
  139. warning(e.message);
  140. }
  141. menu.add(option);
  142. }
  143. private KeyFile theme = new KeyFile();
  144. private void restore_styles() {
  145. try {
  146. loaded_theme = true;
  147. theme.load_from_file(get_data_dir() + "/prefs.ini", KeyFileFlags.NONE);
  148. dark_mode = theme.get_boolean("Theme", "darkmode");
  149. darkmode_button.set_active(dark_mode);
  150. Gtk.Settings.get_default().gtk_application_prefer_dark_theme = dark_mode;
  151. font_size = theme.get_integer("Theme", "fontsize");
  152. font = theme.get_string("Post", "font");
  153. fontstyle = theme.get_string("Post", "fontstyle");
  154. adjust_text_style(false);
  155. } catch (Error err) {/* No biggy... */}
  156. }
  157. private Gtk.CssProvider cur_styles = null;
  158. // So the theme isn't read before it's saved.
  159. private bool loaded_theme = false;
  160. private void adjust_text_style(bool save_theme = true) {
  161. try {
  162. var styles = canvas.get_style_context();
  163. if (cur_styles != null)
  164. Gtk.StyleContext.remove_provider_for_screen(Gdk.Screen.get_default(), cur_styles);
  165. var padding = canvas.get_allocated_width()*0.10;
  166. var css = ("GtkTextView {font: %s; font-size: %dpx; padding: 20px;" +
  167. " padding-left: %ipx; padding-right: %ipx;" +
  168. " -GtkWidget-cursor-color: #5ac4ee;}").printf(font, font_size,
  169. (int) padding, (int) padding);
  170. if (dark_mode) {
  171. // Try to detect whether the system provided a better dark mode.
  172. var text_color = styles.get_color(Gtk.StateFlags.ACTIVE);
  173. double h, s, v;
  174. Gtk.rgb_to_hsv(text_color.red, text_color.green, text_color.blue,
  175. out h, out s, out v);
  176. if (v < 0.5)
  177. css += """GtkTextView {background: black; color: #999;}""";
  178. }
  179. cur_styles = new Gtk.CssProvider();
  180. cur_styles.load_from_data(css);
  181. Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
  182. cur_styles, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
  183. if (save_theme && loaded_theme) {
  184. theme.set_boolean("Theme", "darkmode", dark_mode);
  185. theme.set_integer("Theme", "fontsize", font_size);
  186. theme.set_string("Post", "font", font);
  187. theme.set_string("Post", "fontstyle", fontstyle);
  188. theme.save_to_file(get_data_dir() + "/prefs.ini");
  189. }
  190. } catch (Error e) {
  191. warning(e.message);
  192. }
  193. }
  194. private string publish() {
  195. try {
  196. if (text_changed) {;
  197. draft_file().replace_contents(canvas.buffer.text.data, null, false,
  198. FileCreateFlags.PRIVATE | FileCreateFlags.REPLACE_DESTINATION,
  199. null);
  200. text_changed = false;
  201. }
  202. var cmd = "sh -c 'cat ~/" + data_dir + "/draft.txt | writeas --font %s'";
  203. cmd = cmd.printf(fontstyle);
  204. string stdout, stderr;
  205. int status;
  206. Process.spawn_command_line_sync(cmd,
  207. out stdout, out stderr, out status);
  208. // Open it in the browser
  209. if (status == 0) {
  210. var browser = AppInfo.get_default_for_uri_scheme("https");
  211. var urls = new List<string>();
  212. urls.append(stdout.strip());
  213. browser.launch_uris(urls, null);
  214. }
  215. return stderr.strip();
  216. } catch (Error err) {
  217. return err.message;
  218. }
  219. }
  220. /* --- */
  221. private void build_keyboard_shortcuts() {
  222. /* These operations are not exposed to the UI as buttons,
  223. as most people are very familiar with them and they are not the
  224. focus of this app. */
  225. var accels = new Gtk.AccelGroup();
  226. // App operations
  227. accels.connect(Gdk.Key.W, Gdk.ModifierType.CONTROL_MASK,
  228. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  229. (g,a,k,m) => quit());
  230. accels.connect(Gdk.Key.Q, Gdk.ModifierType.CONTROL_MASK,
  231. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  232. (g,a,k,m) => quit());
  233. // File operations
  234. accels.connect(Gdk.Key.S, Gdk.ModifierType.CONTROL_MASK,
  235. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  236. (g,a,k,m) => save_as());
  237. accels.connect(Gdk.Key.S,
  238. Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK,
  239. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED,
  240. (g,a,k,m) => save_as());
  241. accels.connect(Gdk.Key.O, Gdk.ModifierType.CONTROL_MASK,
  242. Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g, a, k, m) => {
  243. try {
  244. open_file(prompt_file(Gtk.FileChooserAction.OPEN, _("_Open")));
  245. } catch (Error e) {
  246. // It's fine...
  247. }
  248. return true;
  249. });
  250. // Adjust text size
  251. accels.connect(Gdk.Key.minus, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  252. if (font_size < 3) {
  253. return false;
  254. }
  255. if (font_size <= 10) {
  256. font_size -= 1;
  257. } else {
  258. font_size -= 2;
  259. }
  260. adjust_text_style(true);
  261. return true;
  262. });
  263. accels.connect(Gdk.Key.equal, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  264. if (font_size < 10) {
  265. font_size += 1;
  266. } else {
  267. font_size += 2;
  268. }
  269. adjust_text_style(true);
  270. return true;
  271. });
  272. // Toggle theme with Ctrl+T
  273. accels.connect(Gdk.Key.T, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  274. darkmode_button.set_active(!darkmode_button.get_active());
  275. return true;
  276. });
  277. // Publish with Ctrl+Enter
  278. accels.connect(Gdk.Key.Return, Gdk.ModifierType.CONTROL_MASK, Gtk.AccelFlags.VISIBLE | Gtk.AccelFlags.LOCKED, (g,a,k,m) => {
  279. canvas.buffer.text += "\n\n" + publish();
  280. return true;
  281. });
  282. add_accel_group(accels);
  283. }
  284. private bool save_as() {
  285. try {
  286. var file = prompt_file(Gtk.FileChooserAction.SAVE, _("_Save as"));
  287. file.replace_contents(canvas.buffer.text.data, null, false,
  288. FileCreateFlags.PRIVATE | FileCreateFlags.REPLACE_DESTINATION,
  289. null);
  290. } catch (Error e) {
  291. // It's fine...
  292. }
  293. return true;
  294. }
  295. private File prompt_file(Gtk.FileChooserAction mode, string action)
  296. throws UserCancellable {
  297. var file_chooser = new Gtk.FileChooserDialog(action, this, mode,
  298. _("_Cancel"), Gtk.ResponseType.CANCEL,
  299. action, Gtk.ResponseType.ACCEPT);
  300. file_chooser.select_multiple = false;
  301. var filter = new Gtk.FileFilter();
  302. filter.add_mime_type("text/plain");
  303. file_chooser.set_filter(filter);
  304. var resp = file_chooser.run();
  305. file_chooser.close();
  306. if (resp == Gtk.ResponseType.ACCEPT) {
  307. return file_chooser.get_file();
  308. } else {
  309. throw new UserCancellable.USER_CANCELLED("FileChooserDialog");
  310. }
  311. }
  312. public void open_file(File file) throws Error {
  313. uint8[] text;
  314. file.load_contents(null, out text, null);
  315. canvas.buffer.text = (string) text;
  316. }
  317. private bool quit() {
  318. this.close();
  319. return true;
  320. }
  321. }
  322. errordomain WriteAs.UserCancellable {USER_CANCELLED}