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.
 
 
 

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