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.
 
 
 

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