forked from giuspen/cherrytree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupport.py
2031 lines (1953 loc) · 98.5 KB
/
support.py
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: UTF-8 -*-
#
# support.py
#
# Copyright 2009-2019 Giuseppe Penone <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import gtk
import pango
import locale
import os
import webbrowser
import re
import time
import cons
import config
import exports
def get_timestamp_str(timestamp_format, time_float):
"""Get timestamp printable from float"""
try:
encoding = locale.getlocale()[1]
assert encoding is not None
except:
encoding = cons.STR_UTF8
struct_time = time.localtime(time_float)
try:
timestamp_str = time.strftime(timestamp_format, struct_time).decode(encoding)
except:
timestamp_str = time.strftime(config.TIMESTAMP_FORMAT_DEFAULT, struct_time).decode(encoding)
return timestamp_str
def get_word_count(dad):
if dad.curr_buffer:
all_text = unicode(dad.curr_buffer.get_text(*dad.curr_buffer.get_bounds()), cons.STR_UTF8, cons.STR_IGNORE)
word_count = len([w for w in all_text.split() if re.search("\w", w, re.UNICODE)])
else:
word_count = 0
return word_count
def auto_decode_str(in_str, from_clipboard=False):
"""Try to Detect Encoding and Decode"""
try:
import chardet
enc_dict = chardet.detect(in_str)
encoding = enc_dict["encoding"]
encodings = [encoding]
except:
encodings = []
if in_str.startswith("\xEF\xBB\xBF"): # UTF-8 "BOM"
encodings += ["utf-8-sig"]
elif in_str.startswith(("\xFF\xFE", "\xFE\xFF")): # UTF-16 BOMs
encodings += [cons.STR_UTF16]
elif from_clipboard:
if re.search(r"</[a-zA-Z]+>", in_str) is not None:
encodings = [cons.STR_UTF8] + encodings
else:
encodings = [cons.STR_UTF16, cons.STR_UTF8] + encodings
else:
encodings += [cons.STR_UTF16, "utf-16le", cons.STR_UTF8, cons.STR_ISO_8859]
try:
encoding = locale.getdefaultlocale()[1]
assert encoding is not None
encodings.append(encoding)
except:
pass
for enc in encodings:
try:
out_str = in_str.decode(enc)
print enc
break
except: pass
else:
out_str = unicode(in_str, cons.STR_UTF8, cons.STR_IGNORE)
return out_str
def apply_tag_try_node_name(dad, iter_start, iter_end):
"""Apply Link to Node Tag if the text is a node name"""
node_name = dad.curr_buffer.get_text(iter_start, iter_end)
node_dest = dad.get_tree_iter_from_node_name(node_name)
if node_dest:
dad.curr_buffer.select_range(iter_start, iter_end)
property_value = cons.LINK_TYPE_NODE + cons.CHAR_SPACE + str(dad.treestore[node_dest][3])
dad.apply_tag(cons.TAG_LINK, property_value=property_value)
return True
return False
def apply_tag_try_link(dad, iter_end, offset_cursor=None):
"""Try and apply link to previous word (after space or newline)"""
tag_applied = False
iter_start = iter_end.copy()
if iter_start.backward_char() and iter_start.get_char() == cons.CHAR_SQ_BR_CLOSE\
and iter_start.backward_char() and iter_start.get_char() == cons.CHAR_SQ_BR_CLOSE:
curr_state = 0
end_offset = iter_start.get_offset()
while iter_start.backward_char():
curr_char = iter_start.get_char()
if curr_char == cons.CHAR_NEWLINE:
break
if curr_char == cons.CHAR_SQ_BR_OPEN:
if curr_state == 0:
curr_state = 1
else:
curr_state = 2
break
if curr_state == 2:
start_offset = iter_start.get_offset()+2
end_offset = iter_end.get_offset()-2
if apply_tag_try_node_name(dad, dad.curr_buffer.get_iter_at_offset(start_offset),
dad.curr_buffer.get_iter_at_offset(end_offset)):
tag_applied = True
dad.curr_buffer.delete(dad.curr_buffer.get_iter_at_offset(end_offset),
dad.curr_buffer.get_iter_at_offset(end_offset+2))
dad.curr_buffer.delete(dad.curr_buffer.get_iter_at_offset(start_offset-2),
dad.curr_buffer.get_iter_at_offset(start_offset))
if offset_cursor != None:
offset_cursor -= 4
else:
iter_start = iter_end.copy()
while iter_start.backward_char():
curr_char = iter_start.get_char()
if curr_char in cons.WEB_LINK_SEPARATORS:
iter_start.forward_char()
break
num_chars = iter_end.get_offset() - iter_start.get_offset()
if num_chars > 4 and get_next_chars_from_iter_are(iter_start, cons.WEB_LINK_STARTERS):
dad.curr_buffer.select_range(iter_start, iter_end)
link_url = dad.curr_buffer.get_text(iter_start, iter_end)
if link_url[0:3] not in ["htt", "ftp"]: link_url = "http://" + link_url
property_value = cons.LINK_TYPE_WEBS + cons.CHAR_SPACE + link_url
dad.apply_tag(cons.TAG_LINK, property_value=property_value)
tag_applied = True
elif num_chars > 2 and get_is_camel_case(iter_start, num_chars):
if apply_tag_try_node_name(dad, iter_start, iter_end):
tag_applied = True
if tag_applied and offset_cursor != None:
dad.curr_buffer.place_cursor(dad.curr_buffer.get_iter_at_offset(offset_cursor))
return tag_applied
def apply_tag_try_automatic_bounds(dad, text_buffer=None, iter_start=None):
"""Try to Select a Word Forward/Backward the Cursor"""
if not text_buffer: text_buffer = dad.curr_buffer
if not iter_start: iter_start = text_buffer.get_iter_at_mark(text_buffer.get_insert())
iter_end = iter_start.copy()
curr_char = iter_end.get_char()
# 1) select alphanumeric + special
match = re.match('\w', curr_char, re.UNICODE)
if not match and not curr_char in dad.selword_chars:
iter_start.backward_char()
iter_end.backward_char()
curr_char = iter_end.get_char()
match = re.match('\w', curr_char, re.UNICODE)
if not match and not curr_char in dad.selword_chars:
return False
while match or curr_char in dad.selword_chars:
if not iter_end.forward_char(): break # end of buffer
curr_char = iter_end.get_char()
match = re.match('\w', curr_char, re.UNICODE)
iter_start.backward_char()
curr_char = iter_start.get_char()
match = re.match('\w', curr_char, re.UNICODE)
while match or curr_char in dad.selword_chars:
if not iter_start.backward_char(): break # start of buffer
curr_char = iter_start.get_char()
match = re.match('\w', curr_char, re.UNICODE)
if not match and not curr_char in dad.selword_chars: iter_start.forward_char()
# 2) remove non alphanumeric from borders
iter_end.backward_char()
curr_char = iter_end.get_char()
while curr_char in dad.selword_chars:
if not iter_end.backward_char(): break # start of buffer
curr_char = iter_end.get_char()
iter_end.forward_char()
curr_char = iter_start.get_char()
while curr_char in dad.selword_chars:
if not iter_start.forward_char(): break # end of buffer
curr_char = iter_start.get_char()
if iter_end.compare(iter_start) > 0:
text_buffer.move_mark(text_buffer.get_insert(), iter_start)
text_buffer.move_mark(text_buffer.get_selection_bound(), iter_end)
return True
return False
def on_sourceview_event_after_double_click_button1(dad, text_view, event):
"""Called after every Double Click with button 1"""
text_buffer = text_view.get_buffer()
x, y = text_view.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, int(event.x), int(event.y))
iter_start = text_view.get_iter_at_location(x, y)
apply_tag_try_automatic_bounds(dad, text_buffer=text_buffer, iter_start=iter_start)
def on_sourceview_event_after_button_press(dad, text_view, event):
"""Called after every gtk.gdk.BUTTON_PRESS on the SourceView"""
text_buffer = text_view.get_buffer()
if event.button in [1, 2]:
x, y = text_view.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, int(event.x), int(event.y))
text_iter = text_view.get_iter_at_location(x, y)
tags = text_iter.get_tags()
# check whether we are hovering a link
if not tags: tags = []
for tag in tags:
tag_name = tag.get_property("name")
if tag_name and tag_name[0:4] == cons.TAG_LINK:
dad.link_clicked(tag_name[5:], event.button == 2)
return False
if dad.lists_handler.is_list_todo_beginning(text_iter):
if dad.is_curr_node_not_read_only_or_error():
dad.lists_handler.todo_list_rotate_status(text_iter, text_buffer)
elif event.button == 3 and not text_buffer.get_has_selection():
x, y = text_view.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, int(event.x), int(event.y))
text_iter = text_view.get_iter_at_location(x, y)
text_buffer.place_cursor(text_iter)
return False
def on_sourceview_list_change_level(dad, iter_insert, list_info, text_buffer, level_increase):
"""Called at list indent/unindent time"""
if not dad.is_curr_node_not_read_only_or_error(): return
dad.user_active = False
end_offset = dad.lists_handler.get_multiline_list_element_end_offset(iter_insert, list_info)
curr_offset = list_info["startoffs"]
curr_level = list_info["level"]
next_level = curr_level+1 if level_increase else curr_level-1
iter_start = text_buffer.get_iter_at_offset(curr_offset)
prev_list_info = dad.lists_handler.get_prev_list_info_on_level(iter_start, next_level)
#print prev_list_info
if list_info["num"] != 0:
bull_offset = curr_offset + 3*list_info["level"]
if list_info["num"] < 0:
if prev_list_info != None and prev_list_info["num"] < 0:
bull_idx = prev_list_info["num"]*(-1) - 1
else:
idx_old = list_info["num"]*(-1) - 1
idx_offset = idx_old - curr_level % len(dad.chars_listbul)
bull_idx = (next_level + idx_offset) % len(dad.chars_listbul)
dad.replace_text_at_offset(dad.chars_listbul[bull_idx],
bull_offset, bull_offset+1, text_buffer)
else:
idx = list_info["aux"]
if prev_list_info != None and prev_list_info["num"] > 0:
this_num = prev_list_info["num"] + 1
index = prev_list_info["aux"]
else:
this_num = 1
idx_old = list_info["aux"]
idx_offset = idx_old - curr_level % cons.NUM_CHARS_LISTNUM
index = (next_level + idx_offset) % cons.NUM_CHARS_LISTNUM
text_to = str(this_num) + cons.CHARS_LISTNUM[index] + cons.CHAR_SPACE
dad.replace_text_at_offset(text_to, bull_offset,
bull_offset+dad.lists_handler.get_leading_chars_num(list_info["num"]), text_buffer)
iter_start = text_buffer.get_iter_at_offset(curr_offset)
#print "%s -> %s" % (curr_offset, end_offset)
while curr_offset < end_offset:
if level_increase:
text_buffer.insert(iter_start, 3*cons.CHAR_SPACE)
end_offset += 3
iter_start = text_buffer.get_iter_at_offset(curr_offset+3)
else:
text_buffer.delete(iter_start, text_buffer.get_iter_at_offset(curr_offset+3))
end_offset -= 3
iter_start = text_buffer.get_iter_at_offset(curr_offset+1)
if not dad.lists_handler.char_iter_forward_to_newline(iter_start) or not iter_start.forward_char():
break
curr_offset = iter_start.get_offset()
dad.user_active = True
dad.update_window_save_needed("nbuf", True)
def on_sourceview_event_after_scroll(dad, text_view, event):
"""Called after every gtk.gdk.SCROLL on the SourceView"""
if dad.ctrl_down:
if event.direction == gtk.gdk.SCROLL_UP:
dad.zoom_text(True)
elif event.direction == gtk.gdk.SCROLL_DOWN:
dad.zoom_text(False)
return False
def on_sourceview_event_after_key_release(dad, text_view, event):
"""Called after every gtk.gdk.KEY_RELEASE on the SourceView"""
keyname = gtk.gdk.keyval_name(event.keyval)
if dad.ctrl_down:
if keyname in cons.STR_KEYS_CONTROL:
dad.ctrl_down = False
elif keyname in [cons.STR_KEY_RETURN, cons.STR_KEY_SPACE]:
if dad.word_count:
dad.update_selected_node_statusbar_info()
return False
def on_sourceview_event_after_key_press(dad, text_view, event, syntax_highl):
"""Called after every gtk.gdk.KEY_PRESS on the SourceView"""
text_buffer = text_view.get_buffer()
keyname = gtk.gdk.keyval_name(event.keyval)
if not dad.ctrl_down:
if keyname in cons.STR_KEYS_CONTROL:
dad.ctrl_down = True
is_code = syntax_highl not in (cons.RICH_TEXT_ID, cons.PLAIN_TEXT_ID)
if is_code is False and dad.auto_smart_quotes is True and keyname in (cons.STR_KEY_DQUOTE, cons.STR_KEY_SQUOTE):
iter_insert = text_buffer.get_iter_at_mark(text_buffer.get_insert())
if iter_insert:
offset_1 = iter_insert.get_offset()-1
if offset_1 > 0:
if keyname == cons.STR_KEY_DQUOTE:
start_char = cons.CHAR_DQUOTE
char_0 = dad.chars_smart_dquote[0]
char_1 = dad.chars_smart_dquote[1]
else:
start_char = cons.CHAR_SQUOTE
char_0 = dad.chars_smart_squote[0]
char_1 = dad.chars_smart_squote[1]
iter_start = text_buffer.get_iter_at_offset(offset_1-1)
offset_0 = -1
while iter_start:
curr_char = iter_start.get_char()
if curr_char == start_char:
candidate_offset = iter_start.get_offset()
if not iter_start.backward_char() or iter_start.get_char() in [cons.CHAR_NEWLINE, cons.CHAR_SPACE, cons.CHAR_TAB]:
offset_0 = candidate_offset
break
if curr_char == cons.CHAR_NEWLINE: break
if not iter_start.backward_char(): break
if offset_0 >= 0:
dad.replace_text_at_offset(char_0, offset_0, offset_0+1, text_buffer)
dad.replace_text_at_offset(char_1, offset_1, offset_1+1, text_buffer)
elif (event.state & gtk.gdk.SHIFT_MASK):
if keyname == cons.STR_KEY_RETURN:
iter_insert = text_buffer.get_iter_at_mark(text_buffer.get_insert())
if not iter_insert: return False
iter_start = iter_insert.copy()
iter_start.backward_char()
list_info = dad.lists_handler.get_paragraph_list_info(iter_start)
if list_info:
text_buffer.insert(text_buffer.get_iter_at_mark(text_buffer.get_insert()), 3*(1+list_info["level"])*cons.CHAR_SPACE)
elif keyname in (cons.STR_KEY_RETURN, cons.STR_KEY_SPACE):
iter_insert = text_buffer.get_iter_at_mark(text_buffer.get_insert())
if not iter_insert: return False
if syntax_highl == cons.RICH_TEXT_ID:
iter_end_link = iter_insert.copy()
iter_end_link.backward_char()
if apply_tag_try_link(dad, iter_end_link, iter_insert.get_offset()):
iter_insert = text_buffer.get_iter_at_mark(text_buffer.get_insert())
iter_start = iter_insert.copy()
if keyname == cons.STR_KEY_RETURN:
cursor_key_press = iter_insert.get_offset()
#print "cursor_key_press", cursor_key_press
if cursor_key_press == dad.cursor_key_press:
# problem of event-after called twice, once before really executing
return False
if not iter_start.backward_char(): return False
if iter_start.get_char() != cons.CHAR_NEWLINE: return False
if iter_start.backward_char() and iter_start.get_char() == cons.CHAR_NEWLINE:
return False # former was an empty row
list_info = dad.lists_handler.get_paragraph_list_info(iter_start)
if not list_info:
if dad.auto_indent:
iter_start = iter_insert.copy()
former_line_indent = get_former_line_indentation(iter_start)
if former_line_indent: text_buffer.insert_at_cursor(former_line_indent)
return False # former was not a list
# possible enter on empty list element
insert_offset = iter_insert.get_offset()
chars_to_startoffs = 1 + dad.lists_handler.get_leading_chars_num(list_info["num"]) + 3*list_info["level"]
if (insert_offset - list_info["startoffs"]) == chars_to_startoffs:
# enter on empty list element
if list_info["level"] > 0:
on_sourceview_list_change_level(dad, iter_insert, list_info, text_buffer, False)
iter_insert = text_buffer.get_iter_at_mark(text_buffer.get_insert())
iter_list_quit = text_buffer.get_iter_at_offset(iter_insert.get_offset()-1)
else:
iter_list_quit = text_buffer.get_iter_at_offset(list_info["startoffs"])
text_buffer.delete(iter_list_quit, iter_insert)
return False
# list new element
curr_level = list_info["level"]
pre_spaces = 3*curr_level*cons.CHAR_SPACE if curr_level else ""
if list_info["num"] < 0:
index = list_info["num"]*(-1) - 1
text_buffer.insert(iter_insert, pre_spaces+dad.chars_listbul[index]+cons.CHAR_SPACE)
elif list_info["num"] == 0:
text_buffer.insert(iter_insert, pre_spaces+dad.chars_todo[0]+cons.CHAR_SPACE)
else:
new_num = list_info["num"] + 1
index = list_info["aux"]
text_buffer.insert(iter_insert, pre_spaces + str(new_num) + cons.CHARS_LISTNUM[index] + cons.CHAR_SPACE)
new_num += 1
iter_start = text_buffer.get_iter_at_offset(insert_offset)
dad.lists_handler.char_iter_forward_to_newline(iter_start)
list_info = dad.lists_handler.get_next_list_info_on_level(iter_start, curr_level)
#print list_info
while list_info and list_info["num"] > 0:
iter_start = text_buffer.get_iter_at_offset(list_info["startoffs"])
end_offset = dad.lists_handler.get_multiline_list_element_end_offset(iter_start, list_info)
iter_end = text_buffer.get_iter_at_offset(end_offset)
iter_start, iter_end, chars_rm = dad.lists_handler.list_check_n_remove_old_list_type_leading(iter_start, iter_end, text_buffer)
end_offset -= chars_rm
text_buffer.insert(iter_start, str(new_num) + cons.CHARS_LISTNUM[index] + cons.CHAR_SPACE)
end_offset += dad.lists_handler.get_leading_chars_num(new_num)
iter_start = text_buffer.get_iter_at_offset(end_offset)
new_num += 1
list_info = dad.lists_handler.get_next_list_info_on_level(iter_start, curr_level)
else: # keyname == cons.STR_KEY_SPACE
if is_code is False and iter_start.backward_chars(2) and dad.enable_symbol_autoreplace:
if iter_start.get_char() == cons.CHAR_GREATER and iter_start.backward_char():
if iter_start.get_line_offset() == 0:
# at line start
if iter_start.get_char() == cons.CHAR_LESSER:
# "<> " becoming "◇ "
dad.special_char_replace(config.CHARS_LISTBUL_DEFAULT[1], iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_MINUS:
# "-> " becoming "→ "
dad.special_char_replace(config.CHARS_LISTBUL_DEFAULT[4], iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_EQUAL:
# "=> " becoming "⇒ "
dad.special_char_replace(config.CHARS_LISTBUL_DEFAULT[5], iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_MINUS and iter_start.backward_char():
if iter_start.get_char() == cons.CHAR_LESSER:
# "<-> " becoming "↔ "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_DOUBLE, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_MINUS:
# "--> " becoming "→ "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_RIGHT, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_EQUAL and iter_start.backward_char():
if iter_start.get_char() == cons.CHAR_LESSER:
# "<=> " becoming "⇔ "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_DOUBLE2, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_EQUAL:
# "==> " becoming "⇒ "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_RIGHT2, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_MINUS and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_MINUS and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_LESSER:
# "<-- " becoming "← "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_LEFT, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_EQUAL and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_EQUAL and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_LESSER:
# "<== " becoming "⇐ "
dad.special_char_replace(cons.SPECIAL_CHAR_ARROW_LEFT2, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_PARENTH_CLOSE and iter_start.backward_char():
if iter_start.get_char().lower() == "c" and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_PARENTH_OPEN:
# "(c) " becoming "© "
dad.special_char_replace(cons.SPECIAL_CHAR_COPYRIGHT, iter_start, iter_insert, text_buffer)
elif iter_start.get_char().lower() == "r" and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_PARENTH_OPEN:
# "(r) " becoming "® "
dad.special_char_replace(cons.SPECIAL_CHAR_REGISTERED_TRADEMARK, iter_start, iter_insert, text_buffer)
elif iter_start.get_char().lower() == "m" and iter_start.backward_char()\
and iter_start.get_char() == "t" and iter_start.backward_char()\
and iter_start.get_char() == cons.CHAR_PARENTH_OPEN:
# "(tm) " becoming "™ "
dad.special_char_replace(cons.SPECIAL_CHAR_UNREGISTERED_TRADEMARK, iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_STAR and iter_start.get_line_offset() == 0:
# "* " becoming "• " at line start
dad.special_char_replace(config.CHARS_LISTBUL_DEFAULT[0], iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_SQ_BR_CLOSE and iter_start.backward_char():
if iter_start.get_line_offset() == 0 and iter_start.get_char() == cons.CHAR_SQ_BR_OPEN:
# "[] " becoming "☐ " at line start
dad.special_char_replace(dad.chars_todo[0], iter_start, iter_insert, text_buffer)
elif iter_start.get_char() == cons.CHAR_COLON and iter_start.backward_char():
if iter_start.get_line_offset() == 0 and iter_start.get_char() == cons.CHAR_COLON:
# ":: " becoming "▪ " at line start
dad.special_char_replace(config.CHARS_LISTBUL_DEFAULT[2], iter_start, iter_insert, text_buffer)
return False
def sourceview_cursor_and_tooltips_handler(dad, text_view, x, y):
"""Looks at all tags covering the position (x, y) in the text view,
and if one of them is a link, change the cursor to the HAND2 cursor"""
hovering_link_iter_offset = -1
text_iter = text_view.get_iter_at_location(x, y)
if dad.lists_handler.is_list_todo_beginning(text_iter):
text_view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gtk.gdk.Cursor(gtk.gdk.X_CURSOR))
text_view.set_tooltip_text(None)
return
tags = text_iter.get_tags()
if not tags: tags = []
for tag in tags:
tag_name = tag.get_property("name")
if tag_name and tag_name[0:4] == cons.TAG_LINK:
hovering_link_iter_offset = text_iter.get_offset()
tooltip = dad.sourceview_hovering_link_get_tooltip(tag_name[5:])
break
else:
iter_anchor = text_iter.copy()
for i in [0, 1]:
if i == 1: iter_anchor.backward_char()
anchor = iter_anchor.get_child_anchor()
if anchor and "pixbuf" in dir(anchor):
pixbuf_attrs = dir(anchor.pixbuf)
if "link" in pixbuf_attrs and anchor.pixbuf.link:
hovering_link_iter_offset = text_iter.get_offset()
tooltip = dad.sourceview_hovering_link_get_tooltip(anchor.pixbuf.link)
break
if dad.hovering_link_iter_offset != hovering_link_iter_offset:
dad.hovering_link_iter_offset = hovering_link_iter_offset
#print "link", dad.hovering_link_iter_offset
if dad.hovering_link_iter_offset >= 0:
text_view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))
if len(tooltip) > cons.MAX_TOOLTIP_LINK_CHARS:
tooltip = tooltip[:cons.MAX_TOOLTIP_LINK_CHARS] + "..."
text_view.set_tooltip_text(tooltip)
else:
text_view.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(gtk.gdk.Cursor(gtk.gdk.XTERM))
text_view.set_tooltip_text(None)
def rich_text_node_modify_tables_font(start_iter, dad):
"""Modify Font to Tables"""
curr_iter = start_iter.copy()
while 1:
anchor = curr_iter.get_child_anchor()
if anchor and "liststore" in dir(anchor):
for renderer_text in anchor.renderers_text:
renderer_text.set_property('font-desc', pango.FontDescription(dad.pt_font))
anchor.treeview.set_model(None)
anchor.treeview.set_model(anchor.liststore)
if not curr_iter.forward_char(): break
def rich_text_node_modify_codeboxes_font(start_iter, dad):
"""Modify Font to CodeBoxes"""
curr_iter = start_iter.copy()
while 1:
anchor = curr_iter.get_child_anchor()
if anchor and "sourcebuffer" in dir(anchor):
target_font = dad.code_font if anchor.syntax_highlighting != cons.PLAIN_TEXT_ID else dad.pt_font
anchor.sourceview.modify_font(pango.FontDescription(target_font))
if not curr_iter.forward_char(): break
def rich_text_node_modify_codeboxes_color(start_iter, dad):
"""Modify Color to CodeBoxes"""
curr_iter = start_iter.copy()
while 1:
anchor = curr_iter.get_child_anchor()
if anchor and "sourcebuffer" in dir(anchor):
dad.widget_set_colors(anchor.sourceview, dad.rt_def_fg, dad.rt_def_bg, True)
if not curr_iter.forward_char(): break
def text_file_rm_emptylines(filepath):
"""Remove empty lines in a text file"""
overwrite_needed = False
fd = open(filepath, 'r')
file_lines = []
for file_line in fd:
if file_line not in ["\r\n", "\n\r", cons.CHAR_NEWLINE]:
file_lines.append(file_line)
else: overwrite_needed = True
fd.close()
if overwrite_needed:
print filepath, "empty lines removed"
fd = open(filepath, 'w')
fd.writelines(file_lines)
fd.close()
def get_proper_platform_filepath(filepath_in, is_file):
"""From Slash to Backslash when needed"""
filepath_out = filepath_in
if cons.IS_WIN_OS:
if cons.CHAR_SLASH in filepath_in:
filepath_out = filepath_in.replace(cons.CHAR_SLASH, cons.CHAR_BSLASH)
else:
if cons.CHAR_BSLASH in filepath_in:
filepath_out = filepath_in.replace(cons.CHAR_BSLASH, cons.CHAR_SLASH)
return filepath_out
def clean_from_chars_not_for_filename(filename_in):
"""Clean a string from chars not good for filename"""
filename_out = filename_in.replace(cons.CHAR_SLASH, cons.CHAR_MINUS).replace(cons.CHAR_BSLASH, cons.CHAR_MINUS)
filename_out = filename_out.replace(cons.CHAR_STAR, "").replace(cons.CHAR_QUESTION, "").replace(cons.CHAR_COLON, "")
filename_out = filename_out.replace(cons.CHAR_LESSER, "").replace(cons.CHAR_GREATER, "")
filename_out = filename_out.replace(cons.CHAR_PIPE, "").replace(cons.CHAR_DQUOTE, "")
filename_out = filename_out.replace(cons.CHAR_NEWLINE, "").replace(cons.CHAR_CR, "").strip()
return filename_out.replace(cons.CHAR_SPACE, cons.CHAR_USCORE)
def get_node_hierarchical_name(dad, tree_iter, separator="--", for_filename=True, root_to_leaf=True, trailer=""):
"""Get the Node Hierarchical Name"""
hierarchical_name = exports.clean_text_to_utf8(dad.treestore[tree_iter][1]).strip()
father_iter = dad.treestore.iter_parent(tree_iter)
while father_iter:
father_name = exports.clean_text_to_utf8(dad.treestore[father_iter][1]).strip()
if root_to_leaf is True:
hierarchical_name = father_name + separator + hierarchical_name
else:
hierarchical_name = hierarchical_name + separator + father_name
father_iter = dad.treestore.iter_parent(father_iter)
if trailer:
hierarchical_name += trailer
if for_filename is True:
hierarchical_name = clean_from_chars_not_for_filename(hierarchical_name)
if len(hierarchical_name) > cons.MAX_FILE_NAME_LEN:
hierarchical_name = hierarchical_name[-cons.MAX_FILE_NAME_LEN:]
return hierarchical_name
def strip_trailing_spaces(text_buffer):
"""Remove trailing spaces/tabs"""
cleaned_lines = 0
removed_something = True
while removed_something:
removed_something = False
curr_iter = text_buffer.get_start_iter()
curr_state = 0
start_offset = 0
while curr_iter:
curr_char = curr_iter.get_char()
if curr_state == 0:
if curr_char in [cons.CHAR_SPACE, cons.CHAR_TAB]:
start_offset = curr_iter.get_offset()
curr_state = 1
elif curr_state == 1:
if curr_char == cons.CHAR_NEWLINE:
text_buffer.delete(text_buffer.get_iter_at_offset(start_offset), curr_iter)
removed_something = True
cleaned_lines += 1
break
elif not curr_char in [cons.CHAR_SPACE, cons.CHAR_TAB]:
curr_state = 0
if not curr_iter.forward_char():
if curr_state == 1:
text_buffer.delete(text_buffer.get_iter_at_offset(start_offset), curr_iter)
break
return cleaned_lines
def get_is_camel_case(iter_start, num_chars):
"""Returns True if the characters compose a camel case word"""
text_iter = iter_start.copy()
curr_state = 0
for i in range(num_chars):
curr_char = text_iter.get_char()
alphanumeric = re.match('\w', curr_char, re.UNICODE)
if not alphanumeric:
curr_state = -1
break
if curr_state == 0:
if curr_char.islower():
curr_state = 1
elif curr_state == 1:
if curr_char.isupper():
curr_state = 2
elif curr_state == 2:
if curr_char.islower():
curr_state = 3
else:
pass
text_iter.forward_char()
return curr_state == 3
def get_next_chars_from_iter_are(iter_start, chars_list):
"""Returns True if one set of the Given Chars are the first after iter"""
for chars in chars_list:
text_iter = iter_start.copy()
num = len(chars)
for i in range(num):
if text_iter.get_char().encode(cons.STR_UTF8) != chars[i]:
break
if i != num-1 and not text_iter.forward_char():
break
else:
return True
return False
def get_first_chars_of_string_are(in_string, chars_list):
"""Returns True if one set of the Given Chars are the first of in_string"""
for chars in chars_list:
if in_string.startswith(chars):
return True
return False
def get_first_chars_of_string_at_offset_are(in_string, offset, chars_list):
"""Returns True if one set of the Given Chars are the first of in_string"""
for chars in chars_list:
num = len(chars)
for i in range(num):
if in_string[offset+i] != chars[i]:
break
else: return True
return False
def get_former_line_indentation(iter_start):
"""Returns the indentation of the former paragraph or empty string"""
if not iter_start.backward_chars(2) or iter_start.get_char() == cons.CHAR_NEWLINE: return ""
buffer_start = False
while iter_start:
if iter_start.get_char() == cons.CHAR_NEWLINE: break # we got the previous paragraph start
elif not iter_start.backward_char():
buffer_start = True
break # we reached the buffer start
if not buffer_start: iter_start.forward_char()
if iter_start.get_char() == cons.CHAR_SPACE:
num_spaces = 1
while iter_start.forward_char() and iter_start.get_char() == cons.CHAR_SPACE:
num_spaces += 1
return num_spaces*cons.CHAR_SPACE
if iter_start.get_char() == cons.CHAR_TAB:
num_tabs = 1
while iter_start.forward_char() and iter_start.get_char() == cons.CHAR_TAB:
num_tabs += 1
return num_tabs*cons.CHAR_TAB
return ""
def get_pango_weight(is_bold):
"""Get pango weight (integer 200:900) heavy=900, normal=400"""
return pango.WEIGHT_HEAVY if is_bold else pango.WEIGHT_NORMAL
def get_pango_is_bold(weight):
"""Get True if pango weight is bold (heavy)"""
return weight == pango.WEIGHT_HEAVY
def windows_cmd_prepare_path(filepath):
"""Prepares a Path to be digested by windows command line"""
return cons.CHAR_DQUOTE + filepath + cons.CHAR_DQUOTE
def dialog_file_save_as(filename=None, filter_pattern=None, filter_name=None, curr_folder=None, parent=None):
"""The Save file as dialog, Returns the retrieved filepath or None"""
chooser = gtk.FileChooserDialog(title=_("Save File as"),
action=gtk.FILE_CHOOSER_ACTION_SAVE,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT) )
chooser.set_do_overwrite_confirmation(True)
if parent != None:
chooser.set_transient_for(parent)
chooser.set_property("modal", True)
chooser.set_property("destroy-with-parent", True)
chooser.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
else: chooser.set_position(gtk.WIN_POS_CENTER)
if curr_folder == None or os.path.isdir(curr_folder) == False:
chooser.set_current_folder(os.path.expanduser('~'))
else:
chooser.set_current_folder(curr_folder)
if filename != None:
chooser.set_current_name(filename)
if filter_pattern != None:
filter = gtk.FileFilter()
filter.set_name(filter_name)
filter.add_pattern(filter_pattern)
chooser.add_filter(filter)
if chooser.run() == gtk.RESPONSE_ACCEPT:
filepath = chooser.get_filename()
chooser.destroy()
return unicode(filepath, cons.STR_UTF8, cons.STR_IGNORE) if filepath != None else None
else:
chooser.destroy()
return None
def dialog_file_select(filter_pattern=[], filter_mime=[], filter_name=None, curr_folder=None, parent=None):
"""The Select file dialog, Returns the retrieved filepath or None"""
chooser = gtk.FileChooserDialog(title = _("Select File"),
action=gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT) )
if parent != None:
chooser.set_transient_for(parent)
chooser.set_property("modal", True)
chooser.set_property("destroy-with-parent", True)
chooser.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
else: chooser.set_position(gtk.WIN_POS_CENTER)
if curr_folder == None or os.path.isdir(curr_folder) == False:
chooser.set_current_folder(os.path.expanduser('~'))
else:
chooser.set_current_folder(curr_folder)
if filter_pattern or filter_mime:
filefilter = gtk.FileFilter()
filefilter.set_name(filter_name)
for element in filter_pattern:
filefilter.add_pattern(element)
for element in filter_mime:
filefilter.add_mime_type(element)
chooser.add_filter(filefilter)
if chooser.run() == gtk.RESPONSE_ACCEPT:
filepath = chooser.get_filename()
chooser.destroy()
return unicode(filepath, cons.STR_UTF8, cons.STR_IGNORE) if filepath != None else None
else:
chooser.destroy()
return None
def dialog_folder_select(curr_folder=None, parent=None):
"""The Select folder dialog, returns the retrieved folderpath or None"""
chooser = gtk.FileChooserDialog(title = _("Select Folder"),
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT) )
if parent != None:
chooser.set_transient_for(parent)
chooser.set_property("modal", True)
chooser.set_property("destroy-with-parent", True)
chooser.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
else: chooser.set_position(gtk.WIN_POS_CENTER)
if curr_folder == None or os.path.isdir(curr_folder) == False:
chooser.set_current_folder(os.path.expanduser('~'))
else:
chooser.set_current_folder(curr_folder)
if chooser.run() == gtk.RESPONSE_ACCEPT:
folderpath = chooser.get_filename()
chooser.destroy()
return unicode(folderpath, cons.STR_UTF8, cons.STR_IGNORE) if folderpath != None else None
else:
chooser.destroy()
return None
def dialog_question(message, parent=None):
"""The Question dialog, returns True if the user presses OK"""
dialog = gtk.MessageDialog(parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_QUESTION,
message_format=message)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_title(_("Question"))
dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)
dialog.add_button(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
response = dialog.run()
dialog.hide()
return True if response == gtk.RESPONSE_ACCEPT else False
def dialog_info(message, parent):
"""The Info dialog"""
dialog = gtk.MessageDialog(parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_OK,
message_format=message)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_title(_("Info"))
dialog.run()
dialog.destroy()
def dialog_info_after_restart(parent=None):
"""Change Only After Restart"""
dialog_info(_("This Change will have Effect Only After Restarting CherryTree"), parent)
def dialog_warning(message, parent):
"""The Warning dialog"""
dialog = gtk.MessageDialog(parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_OK,
message_format=message)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_title(_("Warning"))
dialog.run()
dialog.destroy()
def dialog_error(message, parent):
"""The Error dialog"""
dialog = gtk.MessageDialog(parent=parent,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_ERROR,
buttons=gtk.BUTTONS_OK,
message_format=message)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_title(_("Error"))
dialog.run()
dialog.destroy()
def dialog_about(dad):
"""Application About Dialog"""
dialog = gtk.AboutDialog()
dialog.set_program_name("CherryTree")
dialog.set_version(cons.VERSION)
dialog.set_copyright("""Copyright © 2009-2017
Giuseppe Penone <[email protected]>""")
dialog.set_comments(_("A Hierarchical Note Taking Application, featuring Rich Text and Syntax Highlighting"))
dialog.set_license(_("""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
"""))
dialog.set_website("http://www.giuspen.com/cherrytree/")
dialog.set_authors(["Giuseppe Penone <[email protected]>"])
dialog.set_artists(["OCAL <http://www.openclipart.org/>", "Zeltak <[email protected]>", "Angelo Penone <[email protected]>"])
dialog.set_translator_credits(_("Armenian")+" (hy) Seda Stamboltsyan <[email protected]>"+cons.CHAR_NEWLINE+
_("Chinese Simplified")+" (zh_CN) Channing Wong <[email protected]>"+cons.CHAR_NEWLINE+
_("Czech")+" (cs) Pavel Fric <[email protected]>"+cons.CHAR_NEWLINE+
_("Dutch")+" (nl) Luuk Geurts, Patrick Vijgeboom <[email protected]>"+cons.CHAR_NEWLINE+
_("Finnish")+" (fi) Henri Kaustinen <[email protected]>"+cons.CHAR_NEWLINE+
_("French")+" (fr) Klaus Becker <[email protected]>"+cons.CHAR_NEWLINE+
_("German")+" (de) Frank Brungräber <[email protected]>"+cons.CHAR_NEWLINE+
_("Greek")+" (el) Delphina <[email protected]>"+cons.CHAR_NEWLINE+
_("Italian")+" (it) Vincenzo Reale <[email protected]>"+cons.CHAR_NEWLINE+
_("Japanese")+" (ja) Piyo <[email protected]>"+cons.CHAR_NEWLINE+
_("Lithuanian")+" (lt) Zygis <[email protected]>"+cons.CHAR_NEWLINE+
_("Polish")+" (pl) Marcin Swierczynski <[email protected]>"+cons.CHAR_NEWLINE+
_("Portuguese Brazil")+" (pt_BR) Vinicius Schmidt <[email protected]>"+cons.CHAR_NEWLINE+
_("Russian")+" (ru) Andriy Kovtun <[email protected]>"+cons.CHAR_NEWLINE+
_("Slovenian")+" (sl) Erik Lovrič <[email protected]>"+cons.CHAR_NEWLINE+
_("Spanish")+" (es) Daniel MC <[email protected]>"+cons.CHAR_NEWLINE+
_("Turkish")+" (tr) Ferhat Aydin <[email protected]>"+cons.CHAR_NEWLINE+
_("Ukrainian")+" (uk) Andriy Kovtun <[email protected]>")
dialog.set_logo(gtk.gdk.pixbuf_new_from_file(os.path.join(cons.GLADE_PATH, "cherrytree.png")))
dialog.set_title(_("About CherryTree"))
dialog.set_transient_for(dad.window)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_modal(True)
def f_url_hook(dialog, link, user_data):
webbrowser.open(link)
gtk.about_dialog_set_url_hook(f_url_hook, None)
dialog.run()
dialog.hide()
def dialog_choose_element_in_list(father_win, title, elements_list, column_title, icon_n_label_list=None):
"""Choose Between Elements in List"""
class ListParms:
def __init__(self):
self.sel_iter = None
list_parms = ListParms()
dialog = gtk.Dialog(title=title,
parent=father_win,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) )
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_default_size(400, 300)
scrolledwindow = gtk.ScrolledWindow()
scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
if not icon_n_label_list: elements_liststore = gtk.ListStore(str)
else: elements_liststore = gtk.ListStore(str,str,str)
elements_treeview = gtk.TreeView(elements_liststore)
elements_renderer_text = gtk.CellRendererText()
if not icon_n_label_list:
elements_column = gtk.TreeViewColumn(column_title, elements_renderer_text, text=0)
else:
elements_treeview.set_headers_visible(False)
renderer_pixbuf = gtk.CellRendererPixbuf()
renderer_text = gtk.CellRendererText()
elements_column = gtk.TreeViewColumn()
elements_column.pack_start(renderer_pixbuf, False)
elements_column.pack_start(renderer_text, True)
elements_column.set_attributes(renderer_pixbuf, stock_id=1)
elements_column.set_attributes(renderer_text, text=2)
elements_treeview.append_column(elements_column)
elements_treeviewselection = elements_treeview.get_selection()
if not icon_n_label_list:
for element_name in elements_list:
elements_liststore.append(element_name)
else:
for element in icon_n_label_list:
elements_liststore.append([element[0], element[1], element[2]])
scrolledwindow.add(elements_treeview)
list_parms.sel_iter = elements_liststore.get_iter_first()
if list_parms.sel_iter:
elements_treeview.set_cursor(elements_liststore.get_path(list_parms.sel_iter))
content_area = dialog.get_content_area()
content_area.pack_start(scrolledwindow)
def on_mouse_button_clicked_elements_list(widget, event):
if event.button != 1: return
if event.type == gtk.gdk._2BUTTON_PRESS:
try: dialog.get_widget_for_response(gtk.RESPONSE_ACCEPT).clicked()
except: print cons.STR_PYGTK_222_REQUIRED
def on_treeview_event_after(treeview, event):
if event.type not in [gtk.gdk.BUTTON_PRESS, gtk.gdk.KEY_PRESS]: return
model, list_parms.sel_iter = elements_treeviewselection.get_selected()
def on_key_press_elementslistdialog(widget, event):
keyname = gtk.gdk.keyval_name(event.keyval)
if keyname == cons.STR_KEY_RETURN:
try: dialog.get_widget_for_response(gtk.RESPONSE_ACCEPT).clicked()
except: print cons.STR_PYGTK_222_REQUIRED
return True
return False
elements_treeview.connect('event-after', on_treeview_event_after)
dialog.connect('key_press_event', on_key_press_elementslistdialog)
elements_treeview.connect('button-press-event', on_mouse_button_clicked_elements_list)
content_area.show_all()
elements_treeview.grab_focus()
response = dialog.run()
dialog.hide()
if response != gtk.RESPONSE_ACCEPT or not list_parms.sel_iter: return ""
return unicode(elements_liststore[list_parms.sel_iter][0], cons.STR_UTF8, cons.STR_IGNORE)
def dialog_img_n_entry(father_win, title, entry_content, img_stock):
"""Insert/Edit Anchor Name"""
dialog = gtk.Dialog(title=title,
parent=father_win,
flags=gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) )
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
dialog.set_default_size(300, -1)
image = gtk.Image()
image.set_from_stock(img_stock, gtk.ICON_SIZE_BUTTON)
entry = gtk.Entry()
entry.set_text(entry_content)
hbox = gtk.HBox()
hbox.pack_start(image, expand=False)
hbox.pack_start(entry)