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.
 
 
 

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