forked from zevlg/telega.el
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telega-core.el
1279 lines (1108 loc) · 49.3 KB
/
telega-core.el
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
;;; telega-core.el --- Core functionality for telega -*- lexical-binding:t -*-
;; Copyright (C) 2018-2019 by Zajcev Evgeny.
;; Author: Zajcev Evgeny <zevlg@yandex.ru>
;; Created: Mon Apr 23 18:09:01 2018
;; Keywords:
;; telega 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.
;; telega 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 telega. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Variables, macroses, defsubst and runtime goodies for telega
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'ring)
(require 'cursor-sensor)
(require 'telega-customize)
(declare-function telega-chat--info "telega-chat" (chat))
(declare-function telega-window-recenter "telega-util" (win &optional nlines from-point))
(declare-function telega-emoji-create-svg "telega-util" (emoji &optional c-height))
(declare-function telega-chats-compare "telega-sort" (criteria chat1 chat2))
(defvar telega--lib-directory nil
"The directory from where this library was first loaded.")
(defconst telega-chat-types
'(private secret basicgroup supergroup bot channel)
"All types of chats supported by telega.")
(defconst telega-mute-for-ever 500000000)
(defconst telega-mute-for-intervals
;; 1h 4h 1d 7d forever
`(3600 14400 86400 604800 ,telega-mute-for-ever))
(defconst telega--slow-mode-delays '(0 10 30 60 300 900 3600)
"List of allowed slow mode delays.")
(defconst telega-chat--chat-permisions
'((:can_send_messages . "lng_rights_chat_send_text")
(:can_send_media_messages . "lng_rights_chat_send_media")
(:can_send_polls . "lng_rights_chat_send_polls")
(:can_send_other_messages . "lng_rights_chat_send_stickers")
(:can_add_web_page_previews . "lng_rights_chat_send_links")
(:can_change_info . "lng_rights_group_info")
(:can_invite_users . "lng_rights_chat_add_members")
(:can_pin_messages . "lng_rights_group_pin")))
(defconst telega-chat--admin-permissions
'((:can_be_edited . "lng_rights_edit_admin")
(:can_manage_chat . nil) ;TODO
(:can_change_info . "lng_rights_group_info")
(:can_post_messages . "lng_rights_channel_post")
(:can_edit_messages . "lng_rights_channel_edit")
(:can_delete_messages . "lng_rights_group_delete")
(:can_invite_users . "lng_rights_group_invite_link")
(:can_pin_messages . "lng_rights_group_pin")
(:can_restrict_members . "telega_rights_restrict_members")
(:can_promote_members . "telega_rights_promote_members")
(:can_manage_voice_chats . "lng_rights_group_manage_calls")
(:is_anonymous . "lng_rights_group_anonymous")))
(defconst telega-notification-scope-types
'((private . "notificationSettingsScopePrivateChats")
(group . "notificationSettingsScopeGroupChats")
(channel . "notificationSettingsScopeChannelChats"))
"Map of lisp name of the scope to TDLib scope type name.")
;;; Runtime variables
(defvar telega--current-buffer nil
"Buffer currently inserting into.
Bind this to make `telega-chars-xxx' family functions to work correctly.
Becase `telega-ins--as-string' uses temporary buffer.")
(defvar telega-msg-contains-unread-mention nil
"Bind this variable when displaying message containing unread mention.")
(defvar telega--chat nil
"Telega chat for the current buffer.
Used in some buffers to refer chat.")
(make-variable-buffer-local 'telega--chat)
(defvar telega--help-win-param nil
"Parameter for the `telega--help-win-redisplay-func'.
Used in help buffers to store some additional data.")
(make-variable-buffer-local 'telega--help-win-param)
(defvar telega--help-win-inserter nil
"Inserter function for the help win.
This function accepts exactly one argument - `telega--help-win-param'.")
(make-variable-buffer-local 'telega--help-win-inserter)
(defvar telega--help-win-dirty-p nil
"Non-nil if help win need redisplay.
Used for optimisations.")
(make-variable-buffer-local 'telega--help-win-dirty-p)
(defvar telega--me-id nil "User id of myself.")
(defvar telega--replies-id nil "Id of the \"Replies\" chat.")
(defvar telega--options nil "Options updated from telega-server.")
(defvar telega--auth-state nil
"Current Authorization state.")
(defvar telega--conn-state nil
"Current connection state.")
(defvar telega--status "Not Started" "Status of the connection to telegram.")
(defvar telega--status-aux
"Aux status used for long requests, such as fetching chats/searching/etc")
(defvar telega--chats nil "Hash table (id -> chat) for all chats.")
(defvar telega--cached-messages nil
"Hash table ((chat-id . msg-id) -> msg) of cached messages.
Such as pinned, replies, etc.")
(defvar telega--actions nil "Hash table (chat-id -> alist-of-user-actions).")
(defvar telega--ordered-chats nil "Ordered list of all chats.")
(defvar telega--filtered-chats nil
"Chats filtered by currently active filters.
Used to calculate numbers displayed in custom filter buttons.")
(defvar telega-deleted-chats nil
"List of recently deleted chats.
Used for \"Recently Deleted Chats\" rootview.")
(defvar telega--dirty-chats nil
"Chats need to be updated with `telega-chat--update'.
Each element is a list, where first element is chat, and rest
is events causing chat to be dirty.")
(defvar telega--filters nil "List of active filters.")
(defvar telega--undo-filters nil "List of undo entries.")
(defvar telega--sort-criteria nil "Active sorting criteria list.")
(defvar telega--sort-inverted nil "Non-nil if sorting is inverted.")
(defvar telega--info nil "Alist of (TYPE . INFO-TABLE).")
(defvar telega--full-info nil "Alist of (TYPE . FULL-INFO-TABLE).")
(defvar telega--top-chats nil
"Alist of (CATEGORY LAST-UPDATE-TIME ..)
CATEGORY is one of `Users', `Bots', `Groups', `Channels',
`InlineBots', `Calls'")
(defvar telega--last-buffer nil
"Used to track buffers switching.
So we can run the code when switching from chat buffer.")
(defvar telega--stickersets nil
"Alist of seen sticker sets.
ID -> sticker set.
Take into account that ID is the string.")
(defvar telega--stickersets-installed-ids nil
"List of ids for installed sticker sets.
Used by `telega-stickerset-installed-p'.")
(defvar telega--stickersets-installed nil
"List of `stickerSetInfo' for installed sticker sets.")
(defvar telega--stickersets-trending nil
"List of trending sticker sets info.")
(defvar telega--stickersets-system nil
"List of system sticker sets, such as animated dices, animated emojis.")
(defvar telega--stickers-favorite nil
"List of favorite stickers.")
(defvar telega--stickers-recent nil
"List of recently used stickers.")
(defvar telega--stickers-recent-attached nil
"List of recently attached stickers.")
(defvar telega--animations-saved nil
"List of saved animations.")
(defvar telega--dice-emojis nil
"List of supported emojis for random dice messages.")
(defvar telega--suggested-actions nil
"List of suggested actions to be taken.")
(defvar telega--group-calls nil "Hash table (id -> group-call).")
;; Searching
(defvar telega-search-history nil
"List of recent search queries.")
(defvar telega--search-chats nil
"Result of last `telega--searchChats' or `telega--searchChatsOnServer'.")
(defvar telega--nearby-chats nil
"List of nearby chats returned from `telega--searchChatsNearby'.")
(defvar telega--unread-message-count nil
"Plist with counts for unread/unmuted messages.
Props are `:unread_count' and `:unread_unmuted_count'")
(defvar telega--unread-chat-count nil
"Plist with counts for unread/unmuted chats.
Props are `:unread_count', `:unread_unmuted_count', `:marked_as_unread_count'
and `:marked_as_unread_unmuted_count'")
(defvar telega--chat-buffers-alist nil
"Alist of chats and corresponding chatbuf.")
(defun telega-chat-buffers ()
"Return list of all chatbufs."
(mapcar #'cdr telega--chat-buffers-alist))
(defvar telega--files nil
"Files hash FILE-ID -> (list FILE UPDATE-CALBACKS..).")
(defvar telega--files-updates nil
"Hash of FILE-ID -> (list-of (UPDATE-CB CB-ARGS))
UPDATE-CB is callback to call when file updates.
UPDATE-CB is called with FILE and CB-ARGS as arguments.
UPDATE-CB should return non-nil to be removed after its being called.")
(defvar telega--proxy-pings nil
"Alist for the proxy pings.
In form (PROXY-ID . TIMESTAMP SECONDS)")
(defvar telega-voip--alist nil
"Alist of all calls currently in processing.
In form (ID . CALL)")
(defvar telega-voip--active-call nil
"Currently active call.
Active call is either outgoing call or accepted incoming call.
Only one call can be currently active.")
(defvar telega--scope-notification-alist (cons nil nil)
"Default notification settings for chats.
alist where key is one of:
\"notificationSettingsScopePrivateChats\",
\"notificationSettingsScopeGroupChats\",
\"notificationSettingsScopeChannelChats\".")
(defvar telega-tdlib--chat-filters nil
"List of chat filters received from TDLib.")
(defvar telega-tdlib--chat-list nil
"Active tdlib chat list used for ordering.")
;; Minibuffer stuff used by chatbuf and stickers
(defvar telega-minibuffer--choices nil
"Bind to list of choices.
Each element in form: (NAME SSET-ID)")
(defvar telega-minibuffer--chat nil
"Bind to chat currently active.")
(defvar telega-minibuffer--string nil
"Bind to Saved string entered to minibuffer.")
(defvar telega--ignored-messages-ring (make-ring 0)
"Ring of ignored messages.
Use \\[execute-extended-command] telega-ignored-messages RET to
display the list.")
(defvar telega-docker--container-id nil
"Docker image id currently running.")
;; See https://github.com/tdlib/td/issues/1645
(defvar telega--relogin-with-phone-number nil
"This var is used to relogin with phone number when skipping QR auth")
;;; Shared chat buffer local variables
(defvar telega-chatbuf--chat nil
"Telega chat for the current chat buffer.")
(make-variable-buffer-local 'telega-chatbuf--chat)
(defun telega-chatbuf--chat (buffer)
"Return chat corresponding chat BUFFER."
(buffer-local-value 'telega-chatbuf--chat buffer))
(defvar telega-chatbuf--marked-messages nil
"List of marked messages.")
(make-variable-buffer-local 'telega-chatbuf--marked-messages)
(defvar telega-chatbuf--marked-messages-1 nil
"List of previously marked messages.")
(make-variable-buffer-local 'telega-chatbuf--marked-messages-1)
(defvar telega-chatbuf--inline-query nil
"Non-nil if some inline bot has been requested.
Actual value is `:@extra` value of the call to inline bot.")
(make-variable-buffer-local 'telega-chatbuf--inline-query)
(defvar telega-chatbuf--input-marker nil)
(make-variable-buffer-local 'telega-chatbuf--input-marker)
(defvar telega-chatbuf--administrators nil
"List of administrators in chatbuf chat.
Asynchronously loaded when chatbuf is created.")
(make-variable-buffer-local 'telega-chatbuf--administrators)
(defvar telega-chatbuf--voice-chat-hidden nil
"Non-nil if non-empty voice chat is displayed in modeline instead of footer.")
(make-variable-buffer-local 'telega-chatbuf--voice-chat-hidden)
(defvar telega-chatbuf--group-call-users nil
"List of group call participants.")
(make-variable-buffer-local 'telega-chatbuf--group-call-users)
(defvar telega-chatbuf--fetch-alist nil
"Alist of async requests (fetches) to the telega-server.
Could be used for fetching `admins', `pinned-messages', `reply-markup', etc.")
(make-variable-buffer-local 'telega-chatbuf--fetch-alist)
(defun telega--init-vars ()
"Initialize runtime variables.
Done when telega server is ready to receive queries."
(setq telega--auth-state nil)
(setq telega--conn-state nil)
(setq telega--status "Disconnected")
(setq telega--status-aux "")
(setq telega--me-id -1)
(setq telega--replies-id nil)
(setq telega--options
;; default limits
(list :message_caption_length_max 1024
:message_text_length_max 4096))
(setq telega--chats (make-hash-table :test #'eq))
(setq telega--cached-messages (make-hash-table :test #'equal))
(setq telega--top-chats nil)
(setq telega--search-chats nil)
(setq telega--nearby-chats nil)
(setq telega-deleted-chats nil)
(setq telega--ordered-chats nil)
(setq telega--filtered-chats nil)
(setq telega--dirty-chats nil)
(setq telega--actions (make-hash-table :test 'eq))
(setq telega--filters nil)
(setq telega--undo-filters nil)
(setq telega--sort-criteria nil)
(setq telega--sort-inverted nil)
(setq telega--info
(list (cons 'user (make-hash-table :test 'eq))
(cons 'secretChat (make-hash-table :test 'eq))
(cons 'basicGroup (make-hash-table :test 'eq))
(cons 'supergroup (make-hash-table :test 'eq))))
(setq telega--full-info
(list (cons 'user (make-hash-table :test 'eq))
(cons 'basicGroup (make-hash-table :test 'eq))
(cons 'supergroup (make-hash-table :test 'eq))))
(setq telega--ignored-messages-ring
(make-ring telega-ignored-messages-ring-size))
(setq telega--unread-message-count nil)
(setq telega--unread-chat-count nil)
(setq telega--files (make-hash-table :test 'eq))
(setq telega--files-updates (make-hash-table :test 'eq))
(setq telega-voip--alist nil)
(setq telega-voip--active-call nil)
(setq telega--proxy-pings nil)
(setq telega--scope-notification-alist nil)
(setq telega--stickersets nil)
(setq telega--stickersets-installed-ids nil)
(setq telega--stickersets-installed nil)
(setq telega--stickersets-trending nil)
(setq telega--stickersets-system nil)
(setq telega--stickers-favorite nil)
(setq telega--stickers-recent nil)
(setq telega--stickers-recent-attached nil)
(setq telega--animations-saved nil)
(setq telega--dice-emojis nil)
(setq telega-tdlib--chat-filters nil)
(setq telega-tdlib--chat-list nil)
(setq telega--group-calls (make-hash-table :test 'eq))
(setq telega-docker--container-id nil)
)
(defun telega-test-env (&optional quiet-p)
"Test Emacs environment.
If QUIET-P is non-nil, then show success message in echo area.
Return non-nil if all tests are passed."
(interactive "P")
;; 62bits for numbers is required
;; i.e. ./configure --with-wide-int
(cl-assert (= most-positive-fixnum 2305843009213693951) nil
"Emacs with wide ints (--with-wide-int) is required")
(cl-assert (= (string-to-number "542353335") 542353335) nil
(concat "Emacs with `(string-to-number \"542353335\") ==> 542353335'"
" is required"))
;; at least 25.1 emacs is required
;; see https://t.me/emacs_telega/1592
(cl-assert (fboundp 'cursor-intangible-mode) nil
"Emacs with `cursor-intangible-mode' is required")
;; For now stick with at least 26.1 Emacs
(cl-assert (string-version-lessp "26.0" emacs-version) nil
(format "At least Emacs 26.0 is required, but you have %s"
emacs-version))
;; imagemagick for images NOT required, we have now fallback in case
;; native image transforms available (newer Emacs)
(cl-assert (or (image-type-available-p 'imagemagick)
(if (telega-x-frame)
(and (fboundp 'image-transforms-p)
(funcall 'image-transforms-p))
;; For TTY-only emacs, images are not required
t))
nil
(concat "Emacs with `imagemagick' support is required."
" (libmagickcore, libmagickwand, --with-imagemagick)"))
;; SVG is no longer required if avatars are disabled (in TTY for example)
(cl-assert (or (image-type-available-p 'svg)
(and (not telega-root-show-avatars)
(not telega-user-show-avatars)
(not telega-chat-show-avatars)))
nil
(concat "Emacs with `svg' support is needed to show avatars. "
"Disable `telega-XXX-show-avatars' or recompile Emacs with svg support"))
(unless quiet-p
(message "Your Emacs is suitable to run telega.el"))
t)
(defmacro telega-save-window-start (start end &rest body)
"Execute BODY saving window start and point.
Window start is saved only if window start is inbetween START and
END."
(declare (indent 2))
(let ((buf-win-sym (gensym))
(win-start (gensym "winstart"))
(win-start-line (gensym)))
`(let* ((,buf-win-sym (get-buffer-window))
(,win-start (when ,buf-win-sym
(window-start ,buf-win-sym)))
(,win-start-line (when (and ,buf-win-sym
(>= ,win-start ,start)
(<= ,win-start ,end))
(1+ (count-lines 1 ,win-start)))))
(unwind-protect
(progn ,@body)
(when (and ,buf-win-sym ,win-start-line)
(save-excursion
(goto-char (point-min))
(forward-line (1- ,win-start-line))
(set-window-start ,buf-win-sym (point) 'noforce)))))))
(defmacro telega-save-excursion (&rest body)
"Execute BODY saving current point as moving marker."
(declare (indent 0))
(let ((pnt-sym (gensym)))
`(let* ((,pnt-sym (copy-marker (point) t)))
(unwind-protect
(progn ,@body)
(goto-char ,pnt-sym)))))
(defmacro telega-save-cursor (&rest body)
"Execute BODY saving cursor's line and column position."
(declare (indent 0))
(let ((line-sym (gensym "line"))
(col-sym (gensym "col")))
`(let ((,line-sym (+ (if (bolp) 1 0) (count-lines 1 (point))))
(,col-sym (current-column)))
(unwind-protect
(progn ,@body)
(goto-char (point-min))
(cl-assert (> ,line-sym 0))
(forward-line (1- ,line-sym))
(move-to-column ,col-sym)))))
(defmacro with-telega-debug-buffer (&rest body)
"Execute BODY only if `telega-debug' is non-nil, making debug buffer current."
`(when telega-debug
(with-current-buffer (get-buffer-create "*telega-debug*")
(telega-save-excursion
,@body))))
(defmacro with-telega-root-buffer (&rest body)
"Execute BODY setting current buffer to root buffer.
Inhibits read-only flag."
(declare (indent 0))
`(when (buffer-live-p (telega-root--buffer))
(with-current-buffer telega-root-buffer-name
(let ((inhibit-read-only t))
(unwind-protect
(progn ,@body)
(set-buffer-modified-p nil))))))
(defmacro with-telega-chatbuf (chat &rest body)
"Execute BODY setting current buffer to chat buffer of CHAT.
Executes BODY only if chat buffer already exists.
If there is no corresponding buffer, then do nothing.
Inhibits read-only flag."
(declare (indent 1))
(let ((bufsym (cl-gensym "buf"))
(chatsym (cl-gensym "chat")))
`(let* ((,chatsym ,chat)
(,bufsym (if (and telega-chatbuf--chat
(eq telega-chatbuf--chat ,chatsym))
(current-buffer)
(cdr (assq ,chatsym telega--chat-buffers-alist)))))
(when (buffer-live-p ,bufsym)
(with-current-buffer ,bufsym
(let ((inhibit-read-only t)
(buffer-undo-list t))
,@body))))))
(defmacro with-telega-help-win (buffer-or-name &rest body)
"Execute BODY in help BUFFER-OR-NAME."
(declare (indent 1))
`(progn
(with-help-window ,buffer-or-name)
(redisplay)
(with-help-window ,buffer-or-name
(set-buffer standard-output)
(setq-local nobreak-char-display nil)
(cursor-sensor-mode 1)
,@body)))
(defun telega-help-win--maybe-redisplay (buffer-or-name for-param)
"Possible redisplay help win with BUFFER-OR-NAME.
If BUFFER-OR-NAME exists and visible then redisplay it."
(when-let ((help-buf (get-buffer buffer-or-name)))
(with-current-buffer help-buf
(when (and (eq for-param telega--help-win-param)
telega--help-win-inserter)
(if (get-buffer-window help-buf)
;; Buffer is visible in some HELP-WIN
(telega-save-window-start (point-min) (point-max)
(telega-save-cursor
(let ((inhibit-read-only t))
(setq telega--help-win-dirty-p nil)
(erase-buffer)
(funcall telega--help-win-inserter
telega--help-win-param))))
;; Buffer is not visible, mark it as dirty, so it will be
;; redisplayed when switched in
(setq telega--help-win-dirty-p t))))))
(defmacro telega-help-message (help-name fmt &rest fmt-args)
"Show once help message formatted with FMT and FMT-ARGS.
Show message only if `telega-help-messages' is non-nil."
(declare (indent 2))
`(when (and telega-help-messages
(not (get 'telega-help-messages ,help-name)))
(put 'telega-help-messages ,help-name t)
(message (concat "Telega: " ,fmt) ,@fmt-args)))
(defsubst telega-debug (fmt &rest args)
"Insert formatted string into debug buffer.
FMT and ARGS are passed directly to `format'."
(with-telega-debug-buffer
(goto-char (point-max))
(insert (apply 'format (cons (concat "%d: " fmt "\n")
(cons (telega-time-seconds) args))))))
(defmacro telega--tl-type (tl-obj)
`(intern (plist-get ,tl-obj :@type)))
(defmacro telega--tl-error-p (tl-obj)
"Return non-nil if TL-OBJ is error object."
`(eq (telega--tl-type ,tl-obj) 'error))
(defmacro telega--tl-get (obj prop1 &rest props)
"`plist-get' which works with multiple arguments.
For example:
`(telega--tl-get obj :prop1 :prop2)' is equivalent to
`(plist-get (plist-get obj :prop1) :prop2)`"
(let ((ret `(plist-get ,obj ,prop1)))
(dolist (prop props)
(setq ret (list 'plist-get ret prop)))
ret))
(defmacro telega--tl-prop (prop1 &rest props)
"Generate function to get property by PROP1 and PROPS.
Uses `telega--tl-get' to obtain the property."
(let ((tl-obj-sym (cl-gensym "tl-obj")))
`(lambda (,tl-obj-sym)
(telega--tl-get ,tl-obj-sym ,prop1 ,@props))))
(defmacro telega--tl-dolist (bind &rest body)
"Execute BODY by traversing plist.
BIND is in form ((PROP VAL) PLIST)."
(declare (indent 1))
`(cl-loop for ,(car bind) on ,(cadr bind)
by #'cddr
do (progn ,@body)))
(defsubst telega-file--size (file)
"Return FILE size."
;; NOTE: fsize is 0 if unknown, in this case esize is approximate
;; size
(let ((fsize (plist-get file :size))
(esize (plist-get file :expected_size)))
(if (zerop fsize) esize fsize)))
(defsubst telega-file--downloaded-p (file)
"Return non-nil if FILE has been downloaded."
(and (telega--tl-get file :local :is_downloading_completed)
(file-exists-p (telega--tl-get file :local :path))))
(defsubst telega-file--downloading-p (file)
"Return non-nil if FILE is downloading right now."
(telega--tl-get file :local :is_downloading_active))
(defsubst telega-file--can-download-p (file)
"Return non-nil if FILE can be downloaded.
May return nil even when `telega-file--downloaded-p' returns non-nil."
(telega--tl-get file :local :can_be_downloaded))
(defsubst telega-file--need-download-p (file)
(and (telega-file--can-download-p file)
(not (telega-file--downloaded-p file))))
(defsubst telega-file--downloaded-size (file)
(telega--tl-get file :local :downloaded_size))
(defsubst telega-file--downloading-progress (file)
"Return progress of FILE downloading as float from 0 to 1."
(color-clamp (/ (float (telega-file--downloaded-size file))
(telega-file--size file))))
(defun telega-file--partially-downloaded-p (file)
"Return non-nil if FILE is partially downloaded."
(and (not (telega-file--downloading-p file))
(< 0 (telega-file--downloading-progress file) 1)))
(defsubst telega-file--uploaded-p (file)
"Return non-nil if FILE has been uploaded."
(telega--tl-get file :remote :is_uploading_completed))
(defsubst telega-file--uploading-p (file)
"Return non-nil if FILE is uploading right now."
(telega--tl-get file :remote :is_uploading_active))
(defsubst telega-file--uploading-progress (file)
"Return progress of FILE uploading as float from 0 to 1."
(color-clamp (/ (float (telega--tl-get file :remote :uploaded_size))
(telega-file--size file))))
(defun telega-file--partially-uploaded-p (file)
"Return non-nil if FILE is partially uploaded."
(and (not (telega-file--uploading-p file))
(< 0 (telega-file--uploading-progress file) 1)))
(defsubst telega--desurrogate-apply-part (part &optional keep-properties)
"Apply PART's `telega-display'"
(let ((part-display (get-text-property 0 'telega-display part)))
(cond (part-display
(if keep-properties
;; keep all properties except for `telega-display'
;; Apply `telega-emoji-p' property as well
(let* ((part-props0 (telega-plist-del
(text-properties-at 0 part) 'telega-display))
(emoji-p (plist-get part-props0 'telega-emoji-p))
(part-props1 (telega-plist-del part-props0 'telega-emoji-p))
;; NOTE: we always create new cell for 'display
;; property as in `image-insert', see comment
;; about this in `image-insert' sources
(addon-props (when (and emoji-p
telega-use-images
telega-emoji-use-images)
(list 'rear-nonsticky '(display)
'display (cons 'image (cdr (telega-emoji-create-svg part-display)))))))
(apply 'propertize part-display (nconc part-props1 addon-props)))
part-display))
(keep-properties part)
(t (substring-no-properties part)))))
(defsubst telega--desurrogate-apply-part-keep-properties (part)
(telega--desurrogate-apply-part part 'keep-props))
(defsubst telega--desurrogate-apply (str &optional no-properties)
"Apply `telega-display' properties to STR.
Resulting in new string with no surrogate pairs.
If NO-PROPERTIES is specified, then do not keep text properties."
(mapconcat (if no-properties
#'telega--desurrogate-apply-part
#'telega--desurrogate-apply-part-keep-properties)
(telega--split-by-text-prop str 'telega-display) ""))
(defsubst telega--tl-unpack (obj)
"Unpack TL object OBJ."
obj)
(defsubst telega--tl-pack (obj)
"Pack object OBJ."
;; Remove text props from strings, etc
(cond ((stringp obj) (substring-no-properties obj))
((vectorp obj) (cl-map 'vector #'telega--tl-pack obj))
((listp obj) (mapcar #'telega--tl-pack obj))
(t obj)))
(defun telega-tl-str (obj prop &optional no-properties)
"Get property PROP from OBJ, desurrogating resulting string.
NO-PROPERTIES is passed directly to `telega--desurrogate-apply'.
Return nil for empty strings.
Also supports \"formattedText\" a value of the OBJ's PROP."
(let* ((prop-val (plist-get obj prop))
(text (if (and (listp prop-val)
(equal (plist-get prop-val :@type) "formattedText"))
(telega--fmt-text-faces prop-val)
prop-val))
(ret (telega--desurrogate-apply text no-properties)))
(unless (string-empty-p ret)
ret)))
(defsubst telega-zerop (value)
"Return non-nil if VALUE is nil or `zerop'."
(or (null value) (zerop value)))
(defsubst telega-replies-p (chat)
"Return non-nil if CHAT is Replies chat."
(eq telega--replies-id (plist-get chat :id)))
(defsubst telega-me-p (msg-sender)
"Return non-nil if MSG-SENDER is me.
MSG-SENDER could be a user or a chat."
(eq telega--me-id (plist-get msg-sender :id)))
(defsubst telega-chat-p (msg-sender)
"Return non-nil if CHAT is Telegram chat."
(and msg-sender (eq 'chat (telega--tl-type msg-sender))))
(defsubst telega-user-p (msg-sender)
"Return non-nil if USER is Telegram user."
(and msg-sender (eq 'user (telega--tl-type msg-sender))))
;;; Formatting
(defun telega-fmt-eval-fill (estr attrs)
"Fill ESTR to `:fill-column' value from ATTRS.
Keeps newlines in ESTR.
Return list of strings."
(let ((fill-column (- (or (plist-get attrs :fill-column) fill-column)
(length (plist-get attrs :fill-prefix)))))
(apply #'nconc
(mapcar (if (plist-get attrs :fill)
(lambda (str)
(split-string
(with-temp-buffer
(insert str)
(fill-region (point-min) (point-max)
(plist-get attrs :fill) t)
(buffer-substring (point-min) (point-max)))
"\n"))
#'list)
(split-string estr "\n")))))
(defun telega-fmt-eval-truncate (estr attrs)
"Apply `:max', `:elide-string' and `:elide-trail' properties from ATTRS to ESTR."
(let* ((max (plist-get attrs :max))
;; NOTE: always apply elide
; (elide (plist-get attrs :elide))
(elide-str (or (plist-get attrs :elide-string) telega-symbol-eliding))
(elide-trail (or (plist-get attrs :elide-trail) 0))
(estr-trail (if (> elide-trail 0) (substring estr (- elide-trail)) ""))
(estr-lead (truncate-string-to-width
estr (- max (string-width elide-str) elide-trail))))
(concat estr-lead elide-str estr-trail)))
;; result)
;; ;; Correct truncstr in case of multibyte chars
;; (while (and (not (string-empty-p estr-lead))
;; (< max (string-width
;; (setq result (concat estr-lead elide-str estr-trail)))))
;; (setq estr-lead (substring estr-lead 0 -1)))
;; result))
(defun telega-fmt-eval-align (estr attrs)
"Apply `:min', `:align' and `:align-symbol' properties from ATTRS to ESTR."
(let* ((min (plist-get attrs :min))
(width (- min (string-width estr)))
(align (plist-get attrs :align))
(align-symbol (or (plist-get attrs :align-symbol) " "))
(left "")
(right ""))
;; Grow `left' and `right' until they have required width
(while (< (string-width left) (/ width 2))
(setq left (concat left align-symbol)))
(while (< (string-width right) (- width (/ width 2)))
(setq right (concat right align-symbol)))
(cl-ecase align
(left (concat estr left right))
(right (concat left right estr))
((center centre) (concat left estr right)))))
(defun telega-fmt-eval-min-max (estr attrs)
"Apply `:min' and `:max' properties from ATTRS to ESTR."
(let ((max (plist-get attrs :max))
(min (plist-get attrs :min))
(estr-width (string-width estr)))
(cond ((and max (> estr-width max))
(telega-fmt-eval-truncate estr attrs))
((and min (< estr-width min))
(telega-fmt-eval-align estr attrs))
(t estr))))
(defun telega-fmt-eval-face (estr attrs)
"Apply `:face' attribute from ATTRS to ESTR."
(let ((face (plist-get attrs :face)))
(when face
(add-face-text-property 0 (length estr) face t estr))
estr))
(defun telega-fmt-eval-attrs (estr attrs)
"Apply all attributes ATTRS to ESTR."
;; Blackmagic for fast execution, but
;; NOTE:
;; - Do not prefix first line
;; - Do not prefix empty lines with blank prefix
;; - If last string is empty, do not prefix it
(let* ((fpx (plist-get attrs :fill-prefix))
(fpx-blank-p (or (not fpx) (string-blank-p fpx)))
(filled-estrs (telega-fmt-eval-fill estr attrs))
(formatted-estrs (list (telega-fmt-eval-min-max
(pop filled-estrs) attrs)))
(festr-tail formatted-estrs))
(while filled-estrs
(let* ((estr (car filled-estrs))
(estr-last-p (not (cdr filled-estrs)))
(festr-elem
(list (telega-fmt-eval-min-max
(concat (unless (and (string-empty-p estr)
(or estr-last-p fpx-blank-p))
fpx)
estr)
attrs))))
(setcdr festr-tail festr-elem)
(setq festr-tail festr-elem)
(setq filled-estrs (cdr filled-estrs))))
(telega-fmt-eval-face
(mapconcat #'identity formatted-estrs "\n")
attrs)))
(defsubst telega-fmt-atom (atom)
"Convert ATOM to string.
NIL yields empty string for the convenience."
(cond ((stringp atom) atom)
((null atom) "")
(t (with-output-to-string
(princ atom)))))
(defun telega-fmt-eval-elem (elem value)
"Format single element ELEM with VALUE."
(let (attrs)
(when (and (not (functionp elem)) (listp elem))
(setq attrs (cdr elem)
elem (car elem)))
(telega-fmt-eval-attrs
(cond ((functionp elem)
(telega-fmt-atom (funcall elem value)))
((symbolp elem)
(telega-fmt-atom (symbol-value elem)))
((listp elem)
(telega-fmt-eval elem value))
(t (telega-fmt-atom elem)))
attrs)))
(defun telega-fmt-eval (fmt-spec value)
"Evaluate simple format FMT-SPEC, applying it to VALUE."
(when (functionp fmt-spec)
(setq fmt-spec (funcall fmt-spec value)))
(let ((fmt-result (if (stringp fmt-spec) fmt-spec "")))
(while (consp fmt-spec)
(when (car fmt-spec)
(setq fmt-result
(concat fmt-result
(telega-fmt-eval-elem (car fmt-spec) value))))
(setq fmt-spec (cdr fmt-spec)))
fmt-result))
(defsubst telega--time-at00 (timestamp &optional decoded-ts)
"Return time at 00:00:001 at TIMESTAMP's day.
Optional DECODED-TS is the result of already applied `decode-time'."
(let ((dt (or decoded-ts (decode-time timestamp))))
(1+ (- (floor timestamp) (* 3600 (nth 2 dt)) (* 60 (nth 1 dt)) (nth 0 dt)))))
;;; Buttons for telega
(defun telega-button--ins-error (_val)
"Default inserter for the `telega' button."
(error "Button `:inserter' is unset"))
;; Make 'telega-button be separate (from 'button) type
(put 'telega-button 'type 'telega)
(put 'telega-button 'keymap button-map)
(put 'telega-button 'action 'telega-button--action)
(put 'telega-button 'rear-nonsticky t)
(put 'telega-button 'face nil)
(put 'telega-button :inserter 'telega-button--ins-error)
(put 'telega-button :value nil)
(put 'telega 'button-category-symbol 'telega-button)
(defun telega-button--action (button)
"Run BUTTON's `:action' function on its `:value'.
Return t if `:action' has been called."
(when-let ((telega-action (button-get button :action)))
(funcall telega-action (button-get button :value))
t))
(defun telega-button--sensor-func (_window oldpos dir)
"Function to be used in `cursor-sensor-functions' text property.
Activates button if cursor enter, deactivates if leaves."
(let ((inhibit-read-only t)
(button-region (telega--region-with-cursor-sensor
(if (eq dir 'entered) (point) oldpos))))
(when button-region
(put-text-property (car button-region) (cdr button-region)
'face (if (eq dir 'entered)
'telega-button-active
'telega-button))
(when (eq dir 'entered)
(telega-button--help-echo (car button-region)))
)))
;; `:help-echo' is also available for buttons
(defun telega-button--help-echo (button)
"Show help message for BUTTON defined by `:help-echo' property."
(when telega-help-messages
(let ((help-echo (or (button-get button :help-echo)
(button-get button 'help-echo))))
(when (functionp help-echo)
(setq help-echo (funcall help-echo (button-get button :value))))
(when help-echo
(message "%s" (eval help-echo))))))
(defun telega-button--insert (button-type value &rest props)
"Insert telega button of BUTTON-TYPE with VALUE and PROPS.
Properties specified in PROPS are retained on
`telega-button--update-value' calls."
(declare (indent 2))
(let ((button (apply 'make-text-button
(prog1 (point)
(funcall (or (plist-get props :inserter)
(button-type-get button-type :inserter))
value))
(point)
:type button-type
:value value
:telega-retain-props
(telega-plist-map (lambda (prop _ignored) prop) props)
props)))
(button-at button)))
(defmacro telega-button--change (button new-button)
"Change BUTTON to NEW-BUTTON."
(declare (indent 1))
(let ((newbutton (gensym "newbutton")))
`(let ((inhibit-read-only t))
(goto-char (button-start ,button))
(let ((,newbutton ,new-button))
(delete-region (point) (button-end ,button))
(set-marker ,button ,newbutton)))))
(defun telega-button--update-value (button new-value &rest props)
"Update BUTTON's value to NEW-VALUE.
Additional properties PROPS are updated in button."
;; NOTE: retain values for properties specified in
;; `telega-button--insert', new PROPS overrides retained props
(let ((new-props nil))
(dolist (rprop (button-get button :telega-retain-props))
(setq new-props (plist-put new-props rprop (button-get button rprop))))
(telega--tl-dolist ((addprop value) props)
(setq new-props (plist-put new-props addprop value)))
(telega-button--change button
(apply #'telega-button--insert (button-type button)
new-value new-props))))
(defun telega-button--observable-p (button)
"Return non-nil if BUTTON is observable in some window.
I.e. shown in some window, see `pos-visible-in-window-p'.
Return nil if button is not visible, `full' if BUTTON is fully
visible, `top' if top is visible and bottom is not, `bottom' if bottom
is visible and top is not, `button' if only BUTTON point is visible."
;; NOTE: BUTTON could be a real button (with value) or simple marker
;; for simple marker do not check top and bottom
(cl-assert (markerp button))
(when-let ((bwin (get-buffer-window (marker-buffer button))))
(let* ((button-p (button-get button :value))
(top-p (when button-p
(pos-visible-in-window-p (button-start button) bwin)))
(bottom-p (when button-p
(pos-visible-in-window-p (button-end button) bwin))))
(cond ((and top-p bottom-p) 'full)
(top-p 'top)
(bottom-p 'bottom)
((pos-visible-in-window-p button bwin) 'button)))))
(defun telega-button--make-observable (button &optional even-if-visible-p)
"Make BUTTON observable in window."
(when (markerp button)
(when-let ((bstart (button-start button))
(bend (button-end button))
(bwin (get-buffer-window (marker-buffer button))))
(unless (and (not even-if-visible-p)
(pos-visible-in-window-p bstart bwin)
(pos-visible-in-window-p bend bwin))
(let ((win-h (window-height bwin))
(button-h (count-lines bstart bend)))
(if (>= button-h (/ win-h 2))
;; NOTE: Always keep at least 2 lines visible above the