-
Notifications
You must be signed in to change notification settings - Fork 1
/
kzrnote.py
1418 lines (1226 loc) · 45.7 KB
/
kzrnote.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
# encoding: utf-8
# vim: sts=4 sw=4 et ft=python foldmethod=marker
APPNAME = "kzrnote"
VIM_DEFAULT = 'vim'
ICONNAME = 'kzrnote'
VERSION='0.2'
# Preamble {{{
import importlib
import json
import locale
import os
import signal
import sys
import time
import urllib.parse
import subprocess
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Vte", "2.91")
import dbus
from dbus.gi_service import ExportedGObject
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GObject, GLib
## "Lazy imports"
uuid = None
Gio = None
Gdk = None
Gtk = None
Vte = None
Pango = None
debug = True
def lazy_import(name, fullname=None):
if globals()[name] is None:
globals()[name] = importlib.import_module(fullname or name)
def plainlog(*args):
for arg in args:
sys.stderr.write(str(arg))
sys.stderr.write(" ")
sys.stderr.write("\n")
def debug_log(*args):
if debug:
sys.stderr.write("%s: " % __name__)
sys.stderr.write(str(time.time()) + " ")
plainlog(*args)
def log(*args):
sys.stderr.write("%s: " % __name__)
sys.stderr.write(str(time.time()) + " ")
plainlog(*args)
def error(*args):
sys.stderr.write("Error: ")
plainlog(*args)
def _(x):
return x
# }}}
# Default configuration {{{
DEFAULT_NOTE_NAME ="Empty Note"
NEW_NOTE_TEMPLATE="Note %s"
MAXTITLELEN=50
WINDOW_SIZE_MAIN = (300, 400)
NOTE_ICON = "gtk-file"
N_RECENT_MENU = 15
DATA_ATTIC="attic"
CACHE_SWP="cache"
CACHE_NOTETITLES="notetitles"
CONFIG_RCTEXT=r"""
" NOTE: This file is overwritten regularly.
so ./notemode.vim
"""
CONFIG_USERRC="user.vim"
CONFIG_VIMRC="%s.vim" % APPNAME
CONFIG_FILENAME="config.json"
VIM_EXTRA_FLAGS=[]
DATA_WELCOME_NOTE="""\
Welcome to kzrnote
..................
As of this writing, no special syntax file
exists for kzrnote, so you're free to use any
mode you would like for each note.
Each note remembers its size and position.
Links are created to other notes if their
title is mentioned, and can be opened with
`gf`
→ Configuring kzrnote
kzrnote has a D-Bus API that allows application
integration as well as full-text search.
There are two commands available
:Note create a new note, or with an
argument, open an existing note.
:DeleteNote delete the current note
"""
DATA_ABOUT_NOTE="""\
Configuring kzrnote
...................
You can edit terminal colors, font and vim executable
in ~/.config/kzrnote/config.json
Example::
{
"colors": {
"foreground": "black",
"background": "white",
"palette": []
},
"font": "DejaVu Sans Mono 10",
"vim": "vim"
}
Where palette is a list of 8, 16, 232 or 256 colors.
(Can also be one string with ; separator).
You can set kzrnote-specific vim settings in the
file ~/.config/kzrnote/user.vim
You can set::
let g:kzrnote_link_notes = 0
to disable linking.
The default configuration is set up to
vigorously autosave all open notes. Persistent
undo is also enabled.
Deleted notes are moved to
~/.local/share/kzrnote/attic
You can set::
let g:kzrnote_autosave = 0
to disable autosaving
kzrnote works best with Vim 7.3. The minimal
configuration to make sure links are highlighted and
that the `:Note` command works is something like the
following::
set nocompatible
syntax on
"""
# }}}
# Note Access {{{
def ensurefile(filename, default_content=None):
"""
ensure @filename exists:
it is touched if it does not exist.
directories in the path are NOT created.
@default_content: bytestring, if not None, to
write into the file by default.
"""
if not os.path.exists(filename):
touch_filename(filename, lcontent=default_content)
return filename
def ensuredir(dirpath):
"""
ensure @dirpath exists and return it again
raises OSError on other error than EEXIST
"""
try:
os.makedirs(dirpath, 0o700)
except FileExistsError:
pass
return dirpath
def get_xdg_dir(xdg_var, fallback):
xdg_dir = os.getenv(xdg_var) or os.path.expanduser(fallback)
return os.path.abspath(os.path.join(xdg_dir, APPNAME))
def get_notesdir():
return get_xdg_dir("XDG_DATA_HOME", "~/.local/share")
def get_config_dir():
return get_xdg_dir("XDG_CONFIG_HOME", "~/.config")
def get_cache_dir():
return get_xdg_dir("XDG_CACHE_HOME", "~/.cache")
## make uris just like gnote
## template note://kzrnote/1823-aa8s9df-1231290
URL_SCHEME = "note"
URL_NETLOC = APPNAME
NOTE_SUFFIX = ".note"
## All uuids we use are this length (characters)
FILENAME_LEN = 36 + len(NOTE_SUFFIX)
### Should we use UTF-8 or locale encoding?
##NOTE_ENCODING="UTF-8"
## Right now we are using locale encoding
def tolocaleencoding(ustr, errors=True):
enc = locale.getpreferredencoding(do_setlocale=False)
if errors:
return ustr.encode(enc)
else:
return ustr.encode(enc, 'replace')
def tofilename(ustr, errors=True):
return ustr
def fromlocaleencoding(lstr, errors=True):
"""
Return a unicode string from the locale-encoded @lstr
"""
enc = locale.getpreferredencoding(do_setlocale=False)
if errors:
return lstr.decode(enc)
else:
return lstr.decode(enc, 'replace')
def tonoteencoding(ustr, errors=True):
"""
Return a byte string in the note encoding from @ustr
"""
return tolocaleencoding(ustr, errors)
def fromnoteencoding(lstr, errors=True):
"""
Return a unicode string from the note-encoded @lstr
"""
return fromlocaleencoding(lstr, errors)
def opennote(filename, mode, **kwargs):
if 'errors' not in kwargs:
kwargs['errors'] = "replace"
return open(filename, mode, **kwargs)
def fromgtkstring(gtkstr):
return gtkstr.decode("utf-8") if isinstance(gtkstr, str) else gtkstr
def toasciiuri(uuri):
return uuri.encode("utf-8") if isinstance(uuri, str) else uuri
def note_uuid_from_filename(filename):
"""
Raises ValueError for invalid filename
"""
if filename.endswith(NOTE_SUFFIX):
return os.path.basename(filename)[:-len(NOTE_SUFFIX)]
raise ValueError
def get_note_uri(filepath):
return "%s://%s/%s" % (URL_SCHEME, URL_NETLOC,
note_uuid_from_filename(filepath))
def get_filename_for_note_uri(uri):
"""
Raises ValueError on invalid url
does not check if it exists
"""
parse = urllib.parse.urlparse(uri)
if parse.scheme != URL_SCHEME or parse.netloc != URL_NETLOC:
raise ValueError("Not a %s://%s/.. URI" % (URL_SCHEME, URL_NETLOC))
if len(parse.path) < 2:
raise ValueError("Invalid path in %s" % uri)
return os.path.join(get_notesdir(), os.path.basename(parse.path)) + NOTE_SUFFIX
def get_filename_for_note_basename(notename):
"""
Leniently accept uuids and file basenames and convert into notes.
Raises ValueError if invalid name or does not exist.
"""
if notename.endswith(NOTE_SUFFIX):
end = -len(NOTE_SUFFIX)
else:
end = None
filename = get_note(os.path.basename(notename)[:end])
if is_note(filename):
return filename
raise ValueError("No note found")
def get_note_paths():
D = get_notesdir()
for x in os.listdir(D):
path = os.path.join(D, x)
if is_note(path):
yield path
def get_note(note_uuid):
return os.path.join(get_notesdir(), note_uuid + NOTE_SUFFIX)
def is_valid_note_filename(filename):
return (filename.startswith(get_notesdir()) and
len(os.path.basename(filename)) == FILENAME_LEN and
filename.endswith(NOTE_SUFFIX))
def is_note(filename):
return is_valid_note_filename(filename) and os.path.exists(filename)
def get_new_note_name():
for retry in range(1000):
name = str(uuid.uuid4())
if not os.path.exists(get_note(name)):
return get_note(name)
raise RuntimeError
def touch_filename(filename, lcontent=None):
"""
Touch non-existing @filename
optionally write the bytestring @lcontent into it
"""
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o666)
if lcontent:
written = 0
while written < len(lcontent):
written += os.write(fd, lcontent[written:])
os.close(fd)
def overwrite_by_rename(filename, lcontent):
"""
Overwrite @filename by writing to a temporary file,
then renaming over the original file.
Write the bytestring @lcontent into it
"""
tmp_filename = "%s.tmp_%d" % (filename, os.getpid())
touch_filename(tmp_filename, lcontent)
os.rename(tmp_filename, filename)
def read_note_contents(filename):
"""
Read @filename which must exist
return a byte string
"""
read = []
with opennote(filename, "r") as fobj:
while 1:
r = fobj.read()
if not r:
break
read.append(r)
return "".join(read)
def try_register_pr_pdeathsig():
"""
Register PR_SET_PDEATHSIG (linux-only) for the calling process
which is a signal delivered when its parent dies.
This should ensure child processes die with the parent.
"""
PR_SET_PDEATHSIG=1
SIGHUP=1
if sys.platform != 'linux2':
return
try:
import ctypes
except ImportError:
return
try:
libc = ctypes.CDLL("libc.so.6")
libc.prctl(PR_SET_PDEATHSIG, SIGHUP)
except (AttributeError, OSError):
pass
class OnceCallback:
"""
Callback that can be registered many times, but is only actually called
once.
"""
_active_callbacks = {}
def __init__(self, name, function):
"""
name of this function invocation - calls are deduplicated by name
"""
self._name = name
self._active_callbacks[name] = function
def __call__(self, *args, **kwargs):
try:
function = self._active_callbacks.pop(self._name)
except KeyError:
return None
return function(*args, **kwargs)
# }}}
class NoteMetadataService (object): # {{{
def __init__(self):
self.storagefile = os.path.join(get_cache_dir(), "metadata")
self.geometries = {}
def load(self):
"""
Load configuration
"""
try:
with open(self.storagefile, 'r') as fobj:
for line in fobj:
parts = line.split()
if len(parts) != 5:
continue
uri = parts[0]
try:
coords = [abs(int(x)) for x in parts[1:]]
except ValueError:
pass
else:
(a,b) = coords[:2]
(c,d) = coords[2:]
self.geometries[uri] = ((a,b), (c,d))
except FileNotFoundError:
pass
def save(self):
"""
Save configuration
"""
with open(self.storagefile, 'w') as outfobj:
for uri, geometry in self.geometries.items():
outfobj.write("%s " % uri)
((a,b), (c,d)) = geometry
outfobj.write("%d %d %d %d" % (a,b,c,d))
outfobj.write("\n")
def update_window_geometry(self, window, event, notefilename):
note_uri = get_note_uri(notefilename)
self.geometries[note_uri] = (window.get_size(), window.get_position())
def get_geometry_for(self, notefilename):
"""
Return a (size, position) tuple for @notefilename
or None if nothing is recorded.
"""
note_uri = get_note_uri(notefilename)
return self.geometries.get(note_uri, None)
class Config:
palette_lengths = (0, 8, 16, 232, 256)
def __init__(self):
CONFIG = ensuredir(get_config_dir())
self.filename = os.path.join(CONFIG, CONFIG_FILENAME)
self.config = {}
def load(self):
try:
with open(self.filename) as f:
self.config = json.load(f)
except FileNotFoundError:
return
except OSError as exc:
error("When reading config:", exc)
return
def get_vim(self):
vim = self.config.get("vim")
if isinstance(vim, str) and vim:
return vim
else:
return VIM_DEFAULT
def get_color(self, name):
fg = self.config.get("colors", {}).get(name)
if fg is None:
return None
return self.parse_color(fg)
@classmethod
def parse_color(cls, colorstring):
c = Gdk.RGBA()
if isinstance(colorstring, str) and c.parse(colorstring):
return c
else:
error("Could not parse color: %r" % (colorstring, ))
return None
def get_palette(self):
palette = self.config.get("colors", {}).get("palette")
if palette is None:
return None
if isinstance(palette, str):
palette = palette.split(";")
if not isinstance(palette, list):
error("Palette must be a list: %r" % (palette, ))
return None
if len(palette) not in self.palette_lengths:
error("Palette must be one of lengths %r (found: %r)" % \
(self.palette_lengths, len(palette)))
return None
res = []
for color in palette:
c = self.parse_color(color)
if c is None:
return None
res.append(c)
assert len(res) in self.palette_lengths
return res
def get_font(self):
font_desc = self.config.get("font")
if not font_desc or not isinstance(font_desc, str):
return None
fd = Pango.FontDescription.from_string(font_desc)
if not fd.get_size():
fd.set_size(10)
return fd
def guess_default_window_size(cols=80, rows=60):
"""
Return size tuple width, height (in pixels)
"""
textview = Gtk.TextView.new()
textview.set_property("monospace", True)
# Find the size of one (monospace) letter
playout = textview.create_pango_layout("X")
ink_r, logical_r = playout.get_pixel_extents()
return (
ink_r.width * cols,
ink_r.height * rows,
)
# }}}
# MainInstance {{{
server_name = "io.github.kupferlauncher.%s" % APPNAME
interface_name = "io.github.kupferlauncher.%s" % APPNAME
object_name = "/io/github/kupferlauncher/%s" % APPNAME
class MainInstance (ExportedGObject):
__gsignals__ = {
"note-created": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,
(GObject.TYPE_STRING, )),
## signature: filepath, bool:user_action
"note-deleted": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,
(GObject.TYPE_STRING, GObject.TYPE_BOOLEAN)),
"title-updated": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,
(GObject.TYPE_STRING, GObject.TYPE_STRING )),
"note-contents-changed": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,
(GObject.TYPE_STRING, )),
"note-opened": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,
(GObject.TYPE_STRING, GObject.TYPE_PYOBJECT)),
## signature: filename, GtkWindow
}
def __init__(self):
"""Create a new service on the Session Bus
Raises RuntimeError on no dbus-connection
Raises NameError if the service already exists
"""
try:
session_bus = dbus.Bus()
except dbus.DBusException:
raise RuntimeError("No D-Bus connection")
if session_bus.name_has_owner(server_name):
raise NameError
bus_name = dbus.service.BusName(server_name, bus=session_bus)
super(MainInstance, self).__init__(conn=session_bus,
object_path=object_name,
bus_name=bus_name)
#gobject.GObject.__init__(self)
self.open_files = {}
self.file_names = {}
self.preload_ids = {}
self.window = None
self.status_icon = None
self.connect("note-deleted", self.on_note_deleted)
self.connect("title-updated", self.on_note_title_updated)
self.connect("note-opened", self.on_note_opened)
self.metadata_service = NoteMetadataService()
self.config = Config()
self.ready_to_display_notes = False
def unregister(self):
dbus.Bus().release_name(server_name)
def wait_for_display_notes(self):
debug_log("Wait for display_notes, setup done: %s" % self.ready_to_display_notes)
while Gtk.events_pending() and not self.ready_to_display_notes:
Gtk.main_iteration()
# }}}
# D-Bus Interface {{{
@dbus.service.method(interface_name, in_signature="", out_signature="s")
def CreateNote(self):
new_note = get_new_note_name()
touch_filename(new_note)
return get_note_uri(new_note)
@dbus.service.method(interface_name, in_signature="s", out_signature="s")
def CreateNamedNote(self, title):
new_note = get_new_note_name()
touch_filename(new_note, tonoteencoding(title))
return get_note_uri(new_note)
@dbus.service.method(interface_name, in_signature="s", out_signature="b")
def DeleteNote(self, uri):
"""
Raises ValueError on invalid @uri
"""
filename = get_filename_for_note_uri(uri)
if is_note(filename):
self.delete_note(filename)
return True
else:
error("Is not a note", uri)
return False
@dbus.service.method(interface_name, in_signature="s", out_signature="b")
def DisplayNote(self, uri):
"""
Raises ValueError on invalid @uri
"""
filename = get_filename_for_note_uri(uri)
if is_note(filename):
self.wait_for_display_notes()
self.display_note_by_file(filename)
return True
else:
error("Is not a note", uri)
return False
@dbus.service.method(interface_name)
def DisplaySearch(self):
return self.KzrnoteCommandline([], '', '')
@dbus.service.method(interface_name, in_signature="s", out_signature="s")
def FindNote(self, linked_title):
"""
Returns "" for not found
"""
filename = self.has_note_by_title(linked_title)
if filename and is_note(filename):
return get_note_uri(filename)
return ""
@dbus.service.method(interface_name, in_signature="s", out_signature="b")
def NoteExists(self, uri):
"""
Raises ValueError on invalid @uri
"""
filename = get_filename_for_note_uri(uri)
return is_note(filename)
@dbus.service.method(interface_name, in_signature="", out_signature="as")
def ListAllNotes(self):
all_notes = []
for note in self.get_note_filenames(True):
all_notes.append(get_note_uri(note))
return all_notes
@dbus.service.method(interface_name, in_signature="s", out_signature="s")
def GetNoteTitle(self, uri):
"""
Raises ValueError on invalid @uri
"""
filename = get_filename_for_note_uri(uri)
if is_note(filename):
return self.ensure_note_title(filename)
return ""
@dbus.service.method(interface_name, in_signature="s", out_signature="u")
def GetNoteChangeDate(self, uri):
"""
Raises ValueError on invalid @uri
Raises OSError for internal filesystem error
"""
filename = get_filename_for_note_uri(uri)
return self.get_note_change_date(filename)
@dbus.service.method(interface_name, in_signature="s", out_signature="s")
def GetNoteContents(self, uri):
"""
Raises ValueError on invalid @uri
Raises UnicodeDecodeError on coding error
"""
filename = get_filename_for_note_uri(uri)
if is_note(filename):
return read_note_contents(filename)
else:
return ""
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def SetNoteContents(self, uri, contents):
"""
Raises ValueError on invalid @uri
Raises UnicodeEncodeError on coding error
"""
filename = get_filename_for_note_uri(uri)
if is_note(filename):
lcontents = tonoteencoding(contents)
overwrite_by_rename(filename, lcontents)
self.emit("note-contents-changed", filename)
return True
else:
return False
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def SetNoteContentsXml(self, uri, contents):
# Easy choice: SetNoteContentsXml broken on Gnote. We can support
# SetNoteCompleteXml
raise NotImplementedError
@dbus.service.method(interface_name, in_signature="sb", out_signature="as")
def SearchNotes(self, query, case_sensistive):
## NOTE: For "compatibility", we are always case sensistive
results = []
grep_cmd = ['/bin/grep', '-l', '-i']
grep_cmd.extend(['-e', query])
grep_cmd.extend(['-r', get_notesdir()])
grep_cmd.append('--include=*%s' % NOTE_SUFFIX)
grep_cmd.extend(['--exclude-dir=%s' % CACHE_SWP,
'--exclude-dir=%s' % DATA_ATTIC])
debug_log(grep_cmd)
p = subprocess.Popen(grep_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
close_fds=True)
cin, cout = (p.stdin, p.stdout)
cin.close()
try:
for line in cout:
line = fromlocaleencoding(line)
debug_log(line)
line = line.strip()
if is_note(line):
results.append(get_note_uri(line))
finally:
cout.close()
return results
@dbus.service.method(interface_name, in_signature="s", out_signature="as")
def GetTagsForNote(self, tagname):
## FIXME
return []
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def AddTagToNote(self, uri, tagname):
## FIXME
raise NotImplementedError
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def RemoveTagFromNote(self, uri, tagname):
## FIXME
raise NotImplementedError
@dbus.service.method(interface_name, in_signature="s", out_signature="as")
def GetAllNotesWithTag(self, tagname):
## FIXME
return []
@dbus.service.method(interface_name, out_signature="s")
def Version(self):
return "%s %s" % (APPNAME, VERSION)
## Kzrnote-specific D-Bus methods
@dbus.service.method(interface_name, in_signature="asss", out_signature="s")
def KzrnoteCommandline(self, uargv, display, desktop_startup_id):
return self.handle_commandline(uargv, display, desktop_startup_id)
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def KzrnoteNew(self, argument, sfilename):
debug_log("KzrnoteNew: %s, %s" % (argument, sfilename))
self.create_open_note(None)
return True
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def KzrnoteDelete(self, argument, sfilename):
debug_log("KzrnoteDelete: %s, %s" % (argument, sfilename))
lfilename = tofilename(sfilename, False)
if not is_note(lfilename):
raise ValueError("Cannot delete %r" % lfilename)
self.delete_note(lfilename)
return True
@dbus.service.method(interface_name, in_signature="ss", out_signature="b")
def KzrnoteOpen(self, argument, sfilename):
debug_log("KzrnoteOpen: %s, %s" % (argument, sfilename))
## Open note either by note uuid or by title
try:
## make sure the filename is a byte string
largument = tofilename(argument, False)
filename = get_filename_for_note_basename(largument)
except ValueError:
filename = self.has_note_by_title(argument, False)
if filename and is_note(filename):
debug_log("Open:", filename)
self.display_note_by_file(filename)
return True
error("Can not open:", largument)
return False
@dbus.service.method(interface_name)
def Quit(self):
Gtk.main_quit()
# }}}
# Note Model {{{
def reload_filemodel(self, model):
model.clear()
for filename in self.get_note_filenames(True):
display_name = self.ensure_note_title(filename)
model.append((filename, display_name))
def model_reassess_file(self, model, filename, addrm=False, change=False):
"""
Examine changed @filename and decide
whether to insert, delete, update it
@addrm: if created/deleted
@change: if changed
"""
if not is_valid_note_filename(filename):
return False
## linear search. Will also hit the most recently
## changed files fast anyway
row_filename, row_title = (None, None)
existed_before = True
rowidx = None
for idx, row in enumerate(model):
row_filename, row_title = row
if row_filename == filename:
rowidx = idx
break
else:
existed_before = False
exists_now = is_note(filename)
if not existed_before and exists_now:
new_title = self.ensure_note_title(filename)
model.insert(0, (filename, new_title))
self.emit("note-created", filename)
elif existed_before and exists_now:
self.reload_file_note_title(filename)
new_title = self.file_names[filename]
## write in new title
model[rowidx] = (filename, new_title)
## Move it to the top
rowpath = (rowidx, )
rowiter = model.get_iter(rowpath)
topiter = model.get_iter((0, ))
model.move_before(rowiter, topiter)
self.emit("note-contents-changed", filename)
elif existed_before and not exists_now:
del model[rowidx]
self.emit("note-deleted", filename, False)
else:
error("File modifed does not exist: %r" % filename)
def get_note_change_date(self, filename):
"""
Get the change date for @filename (as an number)
raises OSError on error when reading @filename
"""
stat_res = os.stat(filename)
return stat_res.st_mtime
def get_note_filenames(self, date_sort=False):
"""
Return a sequence of file paths for all notes
@date_sort: if True, sort by most recent first
"""
filenames = get_note_paths()
if date_sort:
return sorted(filenames,
key=self.get_note_change_date,
reverse=True)
else:
return filenames
def has_note_by_title(self, utitle, case_sensitive=True):
"""
Return (the first) filename if exists, None otherwise
Titles longer than the max length are truncated(!)
"""
utitle = utitle[:MAXTITLELEN]
for filename, note_title in self.file_names.items():
if case_sensitive and note_title == utitle:
return filename
elif not case_sensitive and note_title.lower() == utitle.lower():
return filename
return None
def ensure_note_title(self, filename):
"""make sure we have a title for @filename, and return it for convenience"""
if not filename in self.file_names:
self.reload_file_note_title(filename)
return self.file_names[filename]
def reload_file_note_title(self, filename):
self.file_names[filename] = self.extract_note_title(filename)
self.emit("title-updated", filename, self.file_names[filename])
def extract_note_title(self, filepath):
try:
with opennote(filepath, "r") as f:
for firstline in f:
ufirstline = firstline.strip()
if ufirstline:
return ufirstline[:MAXTITLELEN]
break
except EnvironmentError:
pass
return DEFAULT_NOTE_NAME
# }}}
# GUI {{{
def setup_basic(self):
"""
Setup basic data needed for displaying notes
"""
self.metadata_service.load()
self.config.load()
self.ready_to_display_notes = True
def setup_gui(self):
# notification icon
status_icon = Gtk.StatusIcon.new_from_icon_name(ICONNAME)
status_icon.set_tooltip_text(APPNAME)
status_icon.set_visible(True)
self.status_icon = status_icon
# main window with its toolbar and note list
Gtk.Window.set_default_icon_name(ICONNAME)
self.window = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
self.window.set_default_size(*WINDOW_SIZE_MAIN)
self.list_view = Gtk.TreeView.new()
self.list_store = Gtk.ListStore(GObject.TYPE_STRING,
GObject.TYPE_STRING)
self.list_view.set_model(self.list_store)
cell = Gtk.CellRendererText()
filename_col = Gtk.TreeViewColumn("Note", cell, text=1)
self.list_view.append_column(filename_col)
self.reload_filemodel(self.list_store)
self.list_view.set_rules_hint(True)
self.list_view.set_search_column(1)
self.list_view.show()
self.list_view.connect("row-activated", self.on_list_view_row_activate)
## setup the list view to match searches by any substring
## (the default only matches prefixes)
def search_cmp(model, column, key, miter):
## NOTE: Return *False* for matches
return key not in model.get_value(miter, column).lower()
self.list_view.set_search_equal_func(search_cmp)
toolbar = Gtk.Toolbar()
new = Gtk.ToolButton(stock_id=Gtk.STOCK_NEW)
new.set_label(_("Create _New Note"))
new.set_use_underline(True)
new.set_is_important(True)
new.connect("clicked", self.create_open_note)
delete = Gtk.ToolButton(stock_id=Gtk.STOCK_DELETE)
delete.connect("clicked", self.on_delete_row_cliecked, self.list_view)
delete.set_is_important(True)
quit = Gtk.ToolButton(stock_id=Gtk.STOCK_QUIT)
quit.set_is_important(True)
quit.connect("clicked", Gtk.main_quit)
def toolbar_append(item):
toolbar.insert(item, toolbar.get_n_items())
toolbar_append(new)
toolbar_append(delete)
toolbar_append(quit)
toolbar.show_all()
scrollwin = Gtk.ScrolledWindow()
scrollwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
scrollwin.add(self.list_view)
scrollwin.show()
vbox = Gtk.VBox()
vbox.pack_start(toolbar, False, True, 0)
vbox.pack_start(scrollwin, True, True, 0)
vbox.show()
self.window.add(vbox)
# focus the list so that the user can search immediately