-
Notifications
You must be signed in to change notification settings - Fork 116
/
fontasia
executable file
·954 lines (783 loc) · 34.6 KB
/
fontasia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
#!/usr/bin/env python
# fontasia 0.9:
# List all fonts on the system and let the user group them into categories.
#
# Can be run as a standalone script, or as a GIMP 2.x plug-in font chooser
# (where it shows up as Windows->Fontasia).
#
# Contributors: Akkana Peck, Mikael Magnusson, Michael Schumacher
#
# More info on fontasia: http://shallowsky.com/software/fontasia
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
# Thanks to jan bodnar's ZetCode.com PyGTK/Pango tutorial.
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
# gi.require_version('Pango', '1.0')
from gi.repository import Pango
import re
import os
# Maximum number of faces (in the Pango sense, e.g. italic, bold, extralight)
# to show for a given font family:
MAX_FACES = 27
class FontApp(Gtk.Window):
# CSS for the category buttons. No longer needed, but left in
# as an example of how to apply CSS if needed.
# CSS = '''
# .highlightbtn { background-image: none; background-color: #; }
# '''
def __init__(self):
super(FontApp, self).__init__()
# When the quit button is pressed we'll set the quit flag,
# but won't actually quit -- the caller has to do that
# after checking the selected font.
self.quit = False
self.ignore_callbacks = True
# Pango seems to have no way to get a font family given its name,
# so store all font families when we iterate through them,
# which will happen in update_font_list().
self.font_families = {}
# No categories to start with
self.category_fontlists = []
self.category_buttons = []
self.facebuttons = []
self.DEFAULT_TEXT = "The quick brown fox jumped over the lazy dog"
self.preview_text = self.DEFAULT_TEXT
self.DEFAULT_FONT_SIZE = 18
self.fontsize = self.DEFAULT_FONT_SIZE
self.fancy_list = True
# Default sizes: can be overridden in .config/fontasia/fontasia.conf
self.win_width = 760
self.win_height = 400
self.preview_height = 56
self.list_width = 250
# Have we changed anything, so we need to rewrite the config file?
self.modified = False
self.set_border_width(8)
self.connect("destroy", self.save_and_quit)
self.set_title("Fontasia: Categorize your fonts")
main_vbox = Gtk.VBox(spacing = 10)
self.add(main_vbox)
hbox = Gtk.HBox(spacing = 10)
main_vbox.pack_start(hbox, expand=False, fill=True, padding=0)
#
# The preview
#
self.preview = Gtk.Entry()
# The preview will be however wide the window is, saved from last time
# self.preview.set_width_chars(45)
self.preview.set_text(self.preview_text)
# These don't work: I think because grab_focus_without_selecting()
# (called in render_font()) sets the position to 0.
# self.preview.select_region(-1, -1)
# self.preview.set_position(-1)
# Don't use fallbacks for characters not in the current font.
# This apparently didn't work in Gtk2, and is deprecated in Gtk3.
# al = Pango.AttrList()
# al.insert(Pango.AttrFallback(False, 0, -1))
# self.preview.get_layout().set_attributes(al)
hbox.pack_start(self.preview, expand=True, fill=True, padding=0)
# Quit button
btn = Gtk.Button(label="Quit")
hbox.pack_end(btn, expand=False, fill=True, padding=0)
btn.connect("clicked", self.save_and_quit);
main_hbox = Gtk.HBox(spacing = 10)
main_vbox.add(main_hbox)
#
# Left pane: the font list, a TreeView backed by a ListStore
#
self.sw = Gtk.ScrolledWindow()
self.sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
context = self.create_pango_context()
self.all_families = context.list_families()
self.store = Gtk.ListStore(str)
self.treeview = Gtk.TreeView(model=self.store)
# XXX deprecated
# self.treeview.set_rules_hint(True)
self.store.set_sort_column_id(0, Gtk.SortType.ASCENDING)
# Try to allow multi-selection:
# https://askubuntu.com/a/294035 suggests setting can_focus helps,
# but it doesn't
self.treeview.set_can_focus(True)
# and this used to work, but no longer does:
selection = self.treeview.get_selection()
selection.set_mode(Gtk.SelectionMode.MULTIPLE)
# This doesn't work with multiple selection:
# self.treeview.connect("cursor-changed", self.choose_family);
# but this does:
selection.connect("changed", self.choose_family);
self.sw.add(self.treeview)
self.create_column(self.treeview)
main_hbox.pack_start(self.sw, expand=False, fill=True, padding=0)
#
# Right pane: the controls
#
vbox = Gtk.VBox(spacing=15)
main_hbox.pack_start(vbox, expand=True, fill=True, padding=0)
# Box to hold font size, view category etc.
hbox = Gtk.HBox(spacing=10)
vbox.pack_start(hbox, expand=False, fill=True, padding=0)
# Checkbox for rendering fonts in the font list
self.fancy_btn = Gtk.ToggleButton(label="Fancy list")
self.fancy_btn.set_active(self.fancy_list)
self.fancy_btn.connect("toggled", self.toggle_fancy_list_cb)
hbox.pack_start(self.fancy_btn, expand=False, fill=True, padding=0)
# Button to copy current font name
# btn = Gtk.Button(label="Copy Font Name")
# hbox.pack_end(btn, expand=False)
# btn.connect("clicked", self.copy_font_name);
# Font size
label = Gtk.Label(label="Size:")
hbox.pack_start(label, expand=False, fill=True, padding=0)
adj = Gtk.Adjustment(value=self.fontsize, lower=1, upper=1000,
step_increment=1)
self.sizespin = Gtk.SpinButton(adjustment=adj)
self.sizespin.set_numeric(True)
self.sizespin.connect("value-changed", self.choose_family);
hbox.pack_start(self.sizespin, expand=False, fill=True, padding=0)
#
# View category menu
#
label = Gtk.Label(label="Show Category:")
# This is supposed to right-align the label, but alas it does nothing
# and is now deprecated in Gtk3:
#label.set_alignment(1.0, .5)
# This also doesn't right-align, but the docs are clear on that:
# label.set_justify(Gtk.JUSTIFY_RIGHT)
hbox.pack_start(label, expand=False, fill=True, padding=0)
self.view_cat_combo = Gtk.ComboBoxText()
hbox.pack_start(self.view_cat_combo, expand=False, fill=True, padding=0)
self.combo_connect_id = self.view_cat_combo.connect("changed",
self.combochanged)
#
# Category area
#
frame = Gtk.Frame(label="Categories")
frame.set_shadow_type(Gtk.ShadowType.IN)
vbox.pack_start(frame, expand=False, fill=True, padding=0)
fvbox = Gtk.VBox(spacing=15)
fvbox.props.margin_left = 10
fvbox.props.margin_right = 10
fvbox.props.margin_top = 10
fvbox.props.margin_bottom = 10
frame.add(fvbox)
# The category buttons
self.catbuttonbox = Gtk.FlowBox()
fvbox.pack_start(self.catbuttonbox, expand=False, fill=True, padding=0)
# Categories header row
hbox = Gtk.HBox(spacing=8)
fvbox.pack_start(hbox, expand=False, fill=True, padding=0)
label = Gtk.Label(label="Add category:")
hbox.pack_start(label, expand=False, fill=True, padding=0)
entry = Gtk.Entry()
entry.set_width_chars(20)
hbox.pack_start(entry, expand=False, fill=True, padding=0)
btn = Gtk.Button(label="Add category")
hbox.pack_start(btn, expand=False, fill=True, padding=0)
btn.set_sensitive(False)
btn.connect("clicked", self.add_category, entry);
# The entry and button are tied together:
entry.connect("changed", self.new_cat_entry_changed, btn);
#
# Style area (what Pango calls faces):
#
frame = Gtk.Frame(label="Styles")
# Shadow types don't currently seem to work, but leave it here
# in case it ever starts working
frame.set_shadow_type(Gtk.ShadowType.IN)
vbox.pack_start(frame, expand=False, fill=True, padding=0)
fvbox = Gtk.VBox(spacing=15)
# There doesn't seem to be a way to set margin in general
fvbox.props.margin_left = 10
fvbox.props.margin_right = 10
fvbox.props.margin_top = 10
fvbox.props.margin_bottom = 10
frame.add(fvbox)
# A space for face buttons like Bold, Italic
self.facebuttonbox = Gtk.FlowBox()
fvbox.pack_start(self.facebuttonbox, expand=False, fill=True, padding=0)
#
# Apply the CSS: not currently used.
#
# self.css_provider = Gtk.CssProvider()
# self.apply_CSS(FontApp.CSS)
# Not sure if this could be done earlier
self.preview.get_style_context().add_class("preview")
# Pango can tell us about monospace fonts, so make a special category
# which will be at index 0:
self.add_category("_Monospace")
self.MONOSPACE_CAT_I = 0
# Read in all system and user fonts and update the UI accordingly
self.update_font_list()
#
# Just before showing, update everything:
#
self.read_category_file()
# Set size requests, now that we've read them from the config file:
self.set_default_size(self.win_width, self.win_height)
self.sw.set_size_request(self.list_width, -1)
#self.sw.set_size_request(self.list_width, self.list_height)
self.preview.set_size_request(-1, self.preview_height)
self.choose_family(self.treeview)
# Done with UI, finish showing window
self.show_all()
# Setting size_requests earlier set the *minimum* size,
# but we don't want to do that. So reset the size request
# once the widgets have already been sized.
# Alas, Gtk has no way to just set the size without
# specifying a minimum; size_allocate() is a no-op.
#self.sw.set_size_request(self.list_width, 1)
#self.preview.set_size_request(-1, -1)
self.ignore_callbacks = False
# Try again to set multi-selection mode: sometimes it doesn't work
selection.set_mode(Gtk.SelectionMode.MULTIPLE)
def save_and_quit(self, widget=None):
self.write_category_file()
self.quit = True
# Gtk.main_quit()
def apply_CSS(self, newCSS: str):
try:
self.css_provider.load_from_data(newCSS.encode('UTF-8'))
except gi.repository.GLib.GError as e:
print("GTK Error applying CSS:", e, file=sys.stderr)
print("CSS was:", newCSS, file=sys.stderr)
context = Gtk.StyleContext()
context.add_provider_for_screen(Gdk.Screen.get_default(),
self.css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
def toggle_fancy_list_cb(self, widget):
self.fancy_list = widget.get_active()
self.toggle_fancy_list(self.fancy_list)
#self.update_font_list()
def toggle_fancy_list(self, yesno):
column = self.treeview.get_column(0)
rendererText = column.get_cell_renderers()[0]
if self.fancy_list:
column.set_cell_data_func(rendererText, self.set_list_font)
else:
column.set_cell_data_func(rendererText, None)
rendererText.set_property('font', None)
def set_list_font(self, column, cell, model, iter, user_data):
fontname = model.get_value(iter, 0)
# If the font name ends with a number, we're in trouble --
# Pango will try to interpret the number as a HUGE size.
# Sample fonts to test: Math2, Math3,
# Plain Cred 1978 from ttf-larabie-uncommon.
# A few fonts still give width problems, like
# Radios in Motion and Radios in Motion Hard.
# Scriptina - Alternates and Coca-Cola.
fontname = re.sub('[0-9]+$', '', fontname)
cell.set_property('font', fontname)
def create_column(self, treeView):
rendererText = Gtk.CellRendererText()
column = Gtk.TreeViewColumn("Font name", rendererText, text=0)
column.set_sort_column_id(0)
if self.fancy_list:
column.set_cell_data_func(rendererText, self.set_list_font)
treeView.set_search_column(0)
treeView.append_column(column)
def is_font_in_category(self, fontname, catname):
for i in range(0, len(self.category_buttons)):
if self.category_buttons[i].get_name() == catname:
return ( fontname in self.category_fontlists[i] )
return False
def toggle_font_in_category(self, fontname, catname, set_on):
for i in range(0, len(self.category_buttons)):
if self.category_buttons[i].get_name() == catname:
if set_on:
if fontname not in self.category_fontlists[i]:
self.category_fontlists[i].append(fontname)
else:
if fontname in self.category_fontlists[i]:
self.category_fontlists[i].remove(fontname)
return
#
# This is the callback from the font category togglebuttons.
# It calls toggle_font_in_category.
#
def toggle_cur_font_in_cat(self, button, catname):
# Get the rows corresponding with font families currently selected
selection = self.treeview.get_selection()
model, item = selection.get_selected_rows()
# Read all the selected fonts, not just the first one:
for x in item:
fontname = model[x[0]][0]
self.toggle_font_in_category(fontname, catname, button.get_active())
# self.update_category_buttons(fontname)
self.treeview.grab_focus()
# Update the View Categories combobox:
def update_cats_menu(self):
if self.combo_connect_id:
self.view_cat_combo.handler_block(self.combo_connect_id)
self.view_cat_combo.get_model().clear()
# A recent Gtk3 change requires this or none of the combobox entries
# will appear at all.
self.view_cat_combo.set_entry_text_column(0)
self.view_cat_combo.append_text("All fonts")
for btn in self.category_buttons:
catname = btn.get_name()
item = Gtk.MenuItem(label=catname)
self.view_cat_combo.append_text(catname)
self.view_cat_combo.append_text("All in categories")
self.view_cat_combo.append_text("All uncategorized")
self.view_cat_combo.set_active(0)
if self.combo_connect_id:
self.view_cat_combo.handler_unblock(self.combo_connect_id)
# How to get the active text from a combobox:
def cur_category(self):
model = self.view_cat_combo.get_model()
active = self.view_cat_combo.get_active()
if active < 0:
return None
return model[active][0]
def combochanged(self, widget):
curcat = self.cur_category()
if curcat:
self.update_font_list(curcat)
def update_font_list(self, catname = "All fonts"):
special = (catname[0:3] == "All")
if special:
show_all = (catname == "All fonts")
show_all_in_cats = (catname == "All in categories")
show_all_not_in_cats = (catname == "All uncategorized")
# if show_all or show_all_in_cats:
# for catbtn in self.category_buttons:
# catbtn.set_active(show_all_in_cats)
# Create or clear the list store:
self.store.clear()
# Clear the special _Monospace category too:
self.category_fontlists[self.MONOSPACE_CAT_I] = []
self.font_families = {}
for ff in self.all_families:
fname = ff.get_name()
# Is it monospace?
if ff.is_monospace():
self.category_fontlists[self.MONOSPACE_CAT_I].append(fname)
# Pango doesn't seem to have any way to get the font family object
# from its name. So store all families as a dictionary.
self.font_families[fname] = ff
# Else not a special case. Just check for cat membership:
if not special:
if self.is_font_in_category(fname, catname):
self.store.append([fname])
continue
if show_all:
self.store.append([fname])
continue
if show_all_in_cats:
for catbtn in self.category_buttons:
if self.is_font_in_category(fname, catbtn.get_name()):
self.store.append([fname])
break
if show_all_not_in_cats:
is_in_cat = False
for catbtn in self.category_buttons:
if self.is_font_in_category(fname, catbtn.get_name()):
is_in_cat = True
break
if not is_in_cat:
self.store.append([fname])
continue
# Reset all the button colors, since nothing is selected now
# (eventually might be nice to retain the old selection,
# if it's still in the list):
# XXX Should change this to call set_active()
for btn in self.category_buttons:
self.change_button_color(btn, False)
def select_font_by_name(self, fontname):
"""Select the treeview row matching the given font name, if any.
"""
# OMG, it's so incredibly difficult and undocumented
# to auto-select a row in a treeview!
# Iterate through the treeview
for row, treemodelrow in enumerate(self.store):
# treemodelrow is a gi.overrides.Gtk.TreeModelRow
# treemodelrow[0] is the name of the font
if treemodelrow[0] == fontname:
# print("Matched line", row, treemodelrow[0])
col0 = self.treeview.get_column(0)
self.treeview.set_cursor(row, col0, True)
self.treeview.scroll_to_cell(row)
return
treemodelrow = treemodelrow.get_next()
#
# Lines in the category file look like:
# catname: font, font, font ...
#
def read_category_file(self) :
try:
from win32com.shell import shellcon, shell
homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
except ImportError:
homedir = os.getenv("HOME")
self.cat_file_name = os.path.join(homedir, ".config", "fontasia",
"fontasia.conf")
filename = self.cat_file_name
if not os.access(filename, os.R_OK):
filename = "/etc/xdg/fontasia/defaults"
try:
catfp = open(filename, "r")
while 1:
line = catfp.readline()
if not line: break
line = line.strip()
if line[0] == '#': # Skip comments
continue
if line[0:4] == "set ":
varval = line[4:].strip().split("=")
if varval[0] == "string":
self.preview.set_text(varval[1].strip())
continue
if varval[0] == "fontname":
self.select_font_by_name(varval[1])
continue
if varval[0] == "fontsize":
self.fontsize = int(varval[1])
self.sizespin.set_value(self.fontsize)
continue
if varval[0] == "fancy_list":
self.fancy_list = (varval[1] == "True")
self.fancy_btn.set_active(self.fancy_list)
self.toggle_fancy_list(self.fancy_list)
continue
if varval[0] == "win_width":
self.win_width = int(varval[1])
continue
if varval[0] == "win_height":
self.win_height = int(varval[1])
continue
if varval[0] == "preview_height":
self.preview_height = int(varval[1])
continue
if varval[0] == "list_width":
self.list_width = int(varval[1])
continue
# Arguably should save any other values
# for writing back to the file even though
# we don't understand any others
else:
print("Skipping unknown setting", varval[0])
continue
colon = line.find(":")
if colon < 0:
print("Didn't understand line", line, end='')
continue
catname = line[0:colon].strip()
self.add_category(catname)
line = line[colon+1:].strip()
fonts = line.split(",")
for font in fonts:
font = font.strip()
self.toggle_font_in_category(font, catname, True)
catfp.close()
self.update_cats_menu()
except IOError:
print("No fontasia conf file yet -- Welcome to fontasia!")
# Set up a couple of default categories with likely fonts
# self.add_category('monospace')
# self.toggle_font_in_category('Courier 10 Pitch', 'monospace', True)
# self.toggle_font_in_category('DejaVu Sans Mono', 'monospace', True)
# self.toggle_font_in_category('FreeMono', 'monospace', True)
# self.toggle_font_in_category('Monospace', 'monospace', True)
# self.toggle_font_in_category('Liberation Mono', 'monospace', True)
# self.toggle_font_in_category('Nimbus Mono L', 'monospace', True)
# self.add_category('script')
# self.toggle_font_in_category('Purisa', 'script', True)
# self.toggle_font_in_category('URW Chancery L', 'script', True)
return
def write_category_file(self):
catdir = os.path.dirname(self.cat_file_name)
if not os.path.exists(catdir):
os.mkdir(catdir)
catfp = open(self.cat_file_name, "w")
txt = self.preview.get_text()
if txt != self.DEFAULT_TEXT:
try:
print("set string=" + txt, file=catfp)
except:
print("Problem saving the string; reverting to default string")
curfont = self.current_font_family()
if curfont:
print("set fontname=" + curfont, file=catfp)
fontsize = self.sizespin.get_value()
if fontsize != self.DEFAULT_FONT_SIZE:
print("set fontsize=" + str(int(fontsize)), file=catfp)
# Get the current sizes for the list and the preview
alloc = self.get_allocation()
print("set win_width=" + str(alloc.width), file=catfp)
print("set win_height=" + str(alloc.height), file=catfp)
alloc = self.sw.get_allocation()
print("set list_width=" + str(alloc.width), file=catfp)
alloc = self.preview.get_allocation()
print("set preview_height=" + str(alloc.height), file=catfp)
if not self.fancy_list:
print("set fancy_list=False", file=catfp)
for i in range(0, len(self.category_buttons)):
catname = self.category_buttons[i].get_name()
if catname.startswith('_'):
continue
print(catname + ":", ', '.join(self.category_fontlists[i]),
file=catfp)
catfp.close()
print("Saved to", self.cat_file_name)
def new_cat_entry_changed(self, entry, btn):
btn.set_sensitive(entry.get_text_length() > 0)
def category_exists(self, catname):
for btn in self.category_buttons:
if btn.get_name() == catname:
return True
return False
def add_category(self, newcat, entry=None):
if entry:
newcat = entry.get_text()
# Make sure we don't already have this category:
if (self.category_exists(newcat)):
return
btn = Gtk.ToggleButton(label=newcat)
btn.set_name(newcat)
# self.catbuttonbox.addButton(btn)
self.catbuttonbox.insert(btn, position=-1)
btn.connect("clicked", self.toggle_cur_font_in_cat, newcat);
btn.show()
self.category_buttons.append(btn)
self.category_fontlists.append([])
self.update_cats_menu()
# If any fonts are selected, most likely the user wants them
# added to the new category.
self.toggle_cur_font_in_cat(btn, newcat)
if (entry):
entry.set_text("")
#
# Callback for the main toggle buttons down the right half of the window.
#
#def category_toggle(self, widget, catname):
# self.update_font_list()
def change_button_color(self, btn, yesno):
if yesno:
btn.get_style_context().add_class("highlightbtn")
else:
btn.get_style_context().remove_class("highlightbtn")
def update_category_buttons(self, fontname):
self.ignore_callbacks = True
for i in range(0, len(self.category_buttons)):
if fontname in self.category_fontlists[i]:
self.category_buttons[i].set_active(True)
else:
self.category_buttons[i].set_active(False)
self.ignore_callbacks = False
def current_font_family(self):
selection = self.treeview.get_selection()
model, item = selection.get_selected_rows()
if not item:
return None
# Only render the first font.
return model[item[0][0]][0]
def copy_font_name(self, widget):
"""Copy current font face name to both PRIMARY and CLIPBOARD"""
curfont = self.current_font_family()
atom = Gdk.atom_intern('PRIMARY', True)
clipboard = widget.get_clipboard(atom)
clipboard.set_text(curfont, -1)
atom = Gdk.atom_intern('CLIPBOARD', True)
clipboard = widget.get_clipboard(atom)
clipboard.set_text(curfont, -1)
def render_font(self, family, face):
context = self.preview.get_pango_context()
if face:
fontstr = "%s %s %d" % (family.get_name(), face.get_face_name(),
self.fontsize)
else:
fontstr = family.get_name()
fontdesc = Pango.font_description_from_string(fontstr)
# print("fontdesc:", fontdesc)
# print("fontdesc str:", fontdesc.to_string())
# print("family:", fontdesc.get_family())
# print("size:", fontdesc.get_size())
# print("weight:", fontdesc.get_weight())
# print("stretch:", fontdesc.get_stretch())
# print("style:", fontdesc.get_style())
# print("variant:", fontdesc.get_variant())
# print("variations:", fontdesc.get_variations())
# This works better than context.set_font_description,
# but it's deprecated:
# self.preview.modify_font(fontdesc)
# Another, less reliable way to change an entry's font --
# but it requires getting context = self.preview.get_pango_context()
# earlier, before creating the new fontdesc, for some reason.
context.set_font_description(fontdesc)
# It's not good to grab the focus like this -- the user might
# want focus somewhere else, like in the buttons to try the
# next button. But this is the only way I've found to make
# the GTK Entry actually change to the new font;
# without it, it changes maybe 1/3 of the time.
# Also, this is the only way I've found to keep the text
# from being all selected. You'd think that
# self.preview.select_region(0, 0)
# would do that, but it doesn't.
# (See https://stackoverflow.com/q/20225691 for discussion.)
self.preview.grab_focus_without_selecting()
# Heroic efforts to keep font changes in the Entry from
# making the whole window resize every time.
# GTK offers no way to say "make the damn entry stay the same size."
#self.allow_grow = False
#self.set_property("allow-grow", False)
alloc = self.preview.get_allocation()
if alloc.width > 1 and alloc.height > 1:
self.preview.set_size_request(alloc.width, alloc.height)
# Used to use self.apply_CSS here, but it doesn't handle
# font faces, just families.
self.update_category_buttons(family.get_name())
# Now that we're done changing things,
# allow resizing from the user again:
# Unfortunately this is still too early: the entry still resizes!
# So for now, live with the user not being able to resize smaller.
#self.preview.set_size_request(-1, -1)
@staticmethod
def facename_key(face):
facename = face.get_face_name()
words = facename.split()
lastword = words[-1]
if lastword == "Normal":
lastword = '0 ' + lastword
elif lastword == "Regular":
lastword = '1 ' + lastword
return lastword + ' ' + ' '.join(words)
def choose_family(self, widget):
familyname = self.current_font_family()
if not familyname:
return
# Show buttons for faces within this family (bold, italic etc.)
font_family = self.font_families[familyname]
if not font_family:
print("eek, font families not initialized yet")
return
self.update_category_buttons(familyname)
# font_family.list_faces() may have lots of repeats:
# for instance, JetBrains Mono has two of almost every item.
# So iterate through it looking for repeats.
self.faces = []
facenames = []
basebutton = None
# baseindex is only for debugging and should be removed later
baseindex = None
i = 0
for face in sorted(font_family.list_faces(), key=FontApp.facename_key):
facename = face.get_face_name()
if facename in facenames:
# A lot of fonts have repeated face names
# print(familyname, ": skipping duplicate face", facename)
continue
if i >= MAX_FACES:
# print("eek! Too many face names", len(self.faces))
# print("Truncated to", ', '.join([f.get_face_name()
# for f in self.faces]))
break
facenames.append(facename)
self.faces.append(face)
if i < len(self.facebuttons): # already exists; change its name
btn = self.facebuttons[i]
btn.set_label(facename)
else: # Make a new button
btn = Gtk.ToggleButton(label=facename)
btn.set_active(False)
btn.connect("toggled", self.facebutton_cb, i)
self.facebuttons.append(btn)
self.facebuttonbox.insert(btn, position=-1)
lface = facename.lower()
if lface == "normal":
basebutton = btn
baseindex = i
elif lface == "regular":
basebutton = btn
baseindex = i
i += 1
btn.show()
# hide the unused high-number buttons
self.ignore_callbacks = True
for j, btn in enumerate(self.facebuttons[i:]):
index = i + j
btn.hide()
if btn.get_active():
btn.set_active(False)
self.ignore_callbacks = False
if not basebutton and self.faces:
basebutton = self.facebuttons[0]
baseindex = 0
if basebutton:
# set_active() is documented to call the callback,
# but facebutton_cb is never called here.
basebutton.set_active(True)
# so call it explicitly:
self.facebutton_cb(basebutton, baseindex)
else:
self.render_font(font_family, None)
def facebutton_cb(self, button, index):
if self.ignore_callbacks:
return
family = self.font_families[self.current_font_family()]
face = self.faces[index]
# Toggle off all the other buttons.
# It might be nice to use Gtk.RadioButton, but those
# don't look as good for this application and the docs
# are pretty unclear about how to set them up.
self.ignore_callbacks = True
for i, btn in enumerate(self.facebuttons):
if i != index:
btn.set_active(False)
self.render_font(family, face)
self.ignore_callbacks = False
def show_all_categories(self, widget):
for btn in self.category_buttons:
btn.set_active(False)
self.update_font_list()
def python_fu_fontasia():
fontwin = FontApp()
# fontwin.connect("destroy", Gtk.main_quit)
# Gtk.main()
while not fontwin.quit:
Gtk.main_iteration()
pdb.gimp_context_set_font(fontwin.current_font())
if __name__ == '__main__':
import sys
# Are we being run as a GIMP plug-in?
if sys.argv[0].endswith("gimp"):
from gimpfu import *
register(
"python_fu_fontasia",
"An alternate font chooser.",
"An alternate font chooser.",
"Akkana Peck",
"Akkana Peck",
"2016-2023",
"Fontasia...",
"",
[
# No arguments
],
[],
python_fu_fontasia,
menu = "<Image>/Windows/"
)
# Call GIMP's main loop, which will call python_fu_fontasia
# and handle cleaning up afterward.
main()
sys.exit(0)
# Run in background, give control back to the calling shell
rc = os.fork()
if rc:
sys.exit(0)
fontwin = FontApp()
while not fontwin.quit:
Gtk.main_iteration()
# Trust that the FontApp has already saved new categories, etc.
sys.exit(0)