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