-
Notifications
You must be signed in to change notification settings - Fork 139
/
pmore.c
4400 lines (3860 loc) · 127 KB
/
pmore.c
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
/*
* pmore: piaip's more, a new replacement for traditional pager
*
* piaip's new implementation of pager(more) with mmap,
* designed for unlimilited length(lines).
*
* "pmore" is "piaip's more", NOT "PTT's more"!!!
* pmore is designed for general maple-family BBS systems, not
* specific to any branch.
*
* Author: Hung-Te Lin (piaip), June 2005.
*
* Copyright (c) 2005-2009 Hung-Te Lin <piaip@csie.ntu.edu.tw>
* All rights reserved.
*
* Distributed under a Non-Commercial 4clause-BSD alike license.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display appropriate acknowledgement, like:
* This product includes software developed by Hung-Te Lin (piaip).
* The acknowledgement can be localized with the name unchanged.
* 4. You may not exercise any of the rights granted to you above in any
* manner that is primarily intended for or directed toward commercial
* advantage or private monetary compensation. For avoidance of doubt,
* using in a program providing commercial network service is also
* prohibited.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* MAJOR IMPROVEMENTS:
* - Clean source code, and more readable for mortal
* - Correct navigation
* - Excellent search ability (for correctness and user behavior)
* - Less memory consumption (mmap is not considered anyway)
* - Better support for large terminals
* - Unlimited file length and line numbers
*
* TODO AND DONE:
* - [2005, Initial Release]
* - Optimized speed up with Scroll supporting [done]
* - Wrap long lines [done]
* - Left-right wide navigation [done]
* - DBCS friendly wrap [done]
* - Reenrtance for main procedure [done]
* - Support PTT_PRINTS [done]
* - ASCII Art movie support [done]
* - ASCII Art movie navigation keys [pending]
* - A new optimized terminal base system (piterm) [change -> pfterm]
* -
* - [2007, Interactive Movie Enhancement]
* - New Invisible Frame Header Code [done]
* - Playback Control (pause, stop, skip) [done]
* - Interactive Movie (Hyper-text) [done]
* - Preference System (like board-conf) [done]
* - Traditional Movie Compatible Mode [done]
* - movie: Optimization on relative frame numbers [done]
* - movie: Optimization on named frames (by hash) [pending]
* -
* - (2008) Maple3 BBS porting [done, thanks to hrs113355 for initial work]
* - (2009) movie: add INCLUDE/INTERRUPT command [done]
* - (2009) Better help system [done]
* - (2009) Customizable key and help handler [done]
* - (2009) Customizable footer bar floating prompts [done]
* - (2010) Auto Decompression [done]
* - Reject waterball (instant message) when playing movie
* - Support Anti-anti-idle (ex, PCMan sends up-down)
* - Deal or disable Ctrl-U (invokes userlist then waiting one more key)
* - Virtual Contatenate [pending]
* - Drop ANSI between DBCS words if outputing UTF8 [drop, done by term]
*/
// --------------------------------------------------------------- <FEATURES>
/* These are default values.
* You may override them in your bbs.h or config.h etc etc.
*/
#define PMORE_PRELOAD_SIZE (64*1024L) // on busy system set smaller or undef
#define PMORE_USE_OPT_SCROLL // optimized scroll
#define PMORE_USE_DBCS_WRAP // safe wrap for DBCS.
#define PMORE_USE_ASCII_MOVIE // support ascii movie
#define PMORE_USE_INTERNAL_HELP // display pmore internal help
#define PMORE_USE_REPLYKEY_HINTS // prompt user the keys to reply/commenting
#define PMORE_HAVE_SYNCNOW // system needs calling sync API
#define PMORE_HAVE_VKEY // input system is vkey compatible
#define PMORE_IGNORE_UNKNOWN_NAVKEYS // does not return for all unknown keys
//#define PMORE_AUTONEXT_ON_PAGEFLIP // change file when page up/down reaches end
//#define PMORE_AUTONEXT_ON_RIGHTKEY // change file to next for right key
//#define PMORE_RESTRICT_ANSI_MOVEMENT // user cannot use ANSI escapes to move
#define PMORE_ACCURATE_WRAPEND // try more harder to find file end in wrap mode
#define PMORE_AUTOEXIT_FIRSTPAGE // when prompt=NA, show only page 1
#define PMORE_TRADITIONAL_FULLCOL // to work with traditional ascii arts
#define PMORE_LOG_SYSOP_EDIT // log whenever sysop uses E
#define PMORE_OVERRIDE_TIME // override time format if possible
#define PMORE_EXPAND_ESC_STAR // expand ^[*s style TWBBS variable expansion.
// if you are working with a terminal without ANSI control,
// you are using a poor term (define PMORE_USING_POOR_TERM).
#ifndef USE_PFTERM // pfterm is a good terminal system.
#define PMORE_USING_POOR_TERM
#define PMORE_WORKAROUND_CLRTOEOL // try to work with poor terminal sys
#endif // USE_PFTERM
// -------------------------------------------------------------- </FEATURES>
// ----------------------------------------------------------- <LOCALIZATION>
// Messages for localization are listed here.
#define PMORE_MSG_PROGVER "pmore 2007+"
#define PMORE_MSG_PREF_TITLE \
" piaip's more: " PMORE_MSG_PROGVER " 設定選項 "
#define PMORE_MSG_PREF_TITLE_QRAW \
" piaip's more: " PMORE_MSG_PROGVER " 快速設定 - 色彩(ANSI碼)顯示模式 "
#define PMORE_MSG_HELP_TITLE \
" piaip's more: " PMORE_MSG_PROGVER " 瀏覽程式使用說明"
#define PMORE_MSG_HELP_PAUSE \
"請按任意鍵離開此說明畫面"
#define PMORE_MSG_WARN_FAKEUSERINFO \
" ▲此頁內容會依閱\讀者不同,原文未必有您的資料 "
#define PMORE_MSG_WARN_MOVECMD \
" ▲此頁內容含移位碼,可能會顯示偽造的系統訊息 "
#define PMORE_MSG_SEARCH_KEYWORD \
"[搜尋]關鍵字:"
#define PMORE_MSG_SEARCH_LETTERCASE \
"區分大小寫(Y/N/Q)? "
#define PMORE_MSG_GOTO_PAGE \
"跳至此頁(若要改指定行數請在結尾加.): "
#define PMORE_MSG_GOTO_LINE \
"跳至此行: "
#define PMORE_MSG_QPREF_SUBJECT \
"色彩顯示方式:"
#define PMORE_MSG_QPREF_OPTIONS \
"1.預設格式化內容\t2.原始ANSI控制碼\t3.純文字"
#define PMORE_MSG_QPREF_PROMPT \
"請調整設定 (1-3 可直接選定,\\可切換) 或其它任意鍵結束。"
#define PMORE_MSG_MOVIE_DETECTED \
" ★ 這份文件是可播放的文字動畫,要開始播放嗎? [Y/n]"
#define PMORE_MSG_MOVIE_PLAYOLD_GETTIME \
"這可能是傳統動畫檔, 若要直接播放請輸入速度(秒): "
#define PMORE_MSG_MOVIE_PLAYOLD_AS24L \
"傳統動畫是以 24 行為單位設計的, 要模擬 24 行嗎? (否則會用現在的行數)[Yn] "
#define PMORE_MSG_MOVIE_PAUSE \
" >>> 暫停播放動畫,請按任意鍵繼續或 q 中斷。 <<<"
#define PMORE_MSG_MOVIE_PLAYING \
" >>> 動畫播放中... 可按 q, Ctrl-C 或其它任意鍵停止";
#define PMORE_MSG_MOVIE_INTERACTION_PLAYING \
" >>> 互動式動畫播放中... 可按 q 或 Ctrl-C 停止";
#define PMORE_MSG_MOVIE_INTERACTION_WAITSEL \
" >> 請輸入選項: (互動式動畫播放中,可按 q 或 Ctrl-C 中斷)"
#define PMORE_MSG_MOVIE_INTERACTION_STOPPED \
"已強制中斷互動式系統"
// Colors
#define PMORE_COLOR_HEADER1 \
ANSI_COLOR(47;34)
#define PMORE_COLOR_HEADER2 \
ANSI_COLOR(44;37)
#define PMORE_COLOR_FOOTER1_VIEWALL \
ANSI_COLOR(37;44)
#define PMORE_COLOR_FOOTER1_VIEWNONE \
ANSI_COLOR(33;45)
#define PMORE_COLOR_FOOTER1 \
ANSI_COLOR(34;46)
#define PMORE_COLOR_FOOTER2 \
ANSI_COLOR(1;30;47)
#define PMORE_COLOR_FOOTER3_KEY \
ANSI_COLOR(31)
#define PMORE_COLOR_FOOTER3_TEXT \
ANSI_COLOR(30)
#define PMORE_COLOR_FOOTER3 \
ANSI_COLOR(0;47)
// Preference
// header separator default style
#define MFDISP_SEP_DEFAULT \
MFDISP_SEP_OLD
// promptend modes
#define PMORE_USER_EXIT (1) // exit only if user request to do so.
#define PMORE_AUTO_EXIT (0) // exit when reaching last page (implies movie autoplay)
// ---------------------------------------------------------- </LOCALIZATION>
#include "bbs.h"
// ---------------------------------------------------------------- <PORTING>
// Generic Porting
// ----------------------------------------------------------------
// You need to have following APIs to support pmore:
// vkey(): return user input, with KEY_* translated (igetch())
// vmsg(): print a message at bottom line, pause and return user pressed key
// outc()/outs()/prints(): character/string/formatstr output (w/ANSI ability)
// t_columns / b_lines / t_lines: current terminal dimension
// clear() / clrtobol() / clrtoeol(): screen clear API
// move(): move cursor location
// scroll() / rscroll() / refresh(): scroll / reverse-scroll / refresh screen
// getdata / getdata_buf : query user input
//
// ----------------------------------------------------------------
// Maple3 Porting
// ----------------------------------------------------------------
// To use pmore in Maple3(itoc), you need to:
// (1) [config.h] #define M3_USE_PMORE
// (2) [more.c] more(): comment the block between fimage:
// #ifdef M3_USE_PMORE
// + cmd = pmore(fpath, footer && footer != (char*)-1);
// +#else
// if (!(fimage = f_img(fpath, &fsize)))
// .....................................................
// free(fimage);
// +#endif // M3_USE_PMORE
// if (!cmd) /* ...
// (3) if you want to override to override any special keys
// or help pages, you may change to pmore2 and write
// your own key_handler and help_handler.
#ifdef M3_USE_PMORE
// input/output API
#define getdata(y,x,msg,buf,size,mode) vget(y,x,msg,buf,size,mode)
#define getdata_buf(y,x,msg,buf,size,mode) vget(y,x,msg,buf,size,GCARRY|mode)
#define outs(x) outs((unsigned char*)(x))
// variables
#define t_lines (b_lines + 1)
#define t_columns (b_cols + 1)
// key mapping
#define RELATE_PREV '['
#define RELATE_NEXT ']'
#define READ_NEXT 'j'
#define READ_PREV 'k'
#if !defined(FULLUPDATE) && defined(XO_HEAD)
# define FULLUPDATE XO_HEAD
#endif
// environments and features
#undef PMORE_USE_INTERNAL_HELP
#undef PMORE_USE_REPLYKEY_HINTS
#undef PMORE_HAVE_SYNCNOW
#undef PMORE_HAVE_VKEY
#undef PMORE_IGNORE_UNKNOWN_NAVKEYS
#undef PMORE_AUTOEXIT_FIRSTPAGE
#define PMORE_AUTONEXT_ON_PAGEFLIP
#define PMORE_AUTONEXT_ON_RIGHTKEY
#ifndef SHOW_USER_IN_TEXT
# undef PMORE_EXPAND_ESC_STAR
#endif // !SHOW_USER_IN_TEXT
// disable CLRTOEOL workaround: old M3 may has problem with FORCE_CLRTOEOL... you can comment this if your system is OK with it.
#define PMORE_NO_FORCE_CLRTOEOL
// use m3 style separator [none]: comment these if you like Maple2.36/SOB/PTT style
#undef MFDISP_SEP_DEFAULT
#define MFDISP_SEP_DEFAULT MFDISP_SEP_NONE
// theme: comment these if you like pmore style
#undef PMORE_COLOR_HEADER1
#undef PMORE_COLOR_HEADER2
#undef PMORE_COLOR_FOOTER1
#undef PMORE_COLOR_FOOTER1_VIEWALL
#undef PMORE_COLOR_FOOTER1_VIEWNONE
#undef PMORE_COLOR_FOOTER2
#undef PMORE_COLOR_FOOTER3_KEY
#undef PMORE_COLOR_FOOTER3_TEXT
#undef PMORE_COLOR_FOOTER3
#define PMORE_COLOR_HEADER1 COLOR5
#define PMORE_COLOR_HEADER2 COLOR6
#define PMORE_COLOR_FOOTER1_VIEWALL COLOR1
#define PMORE_COLOR_FOOTER1_VIEWNONE COLOR1
#define PMORE_COLOR_FOOTER1 COLOR1
#define PMORE_COLOR_FOOTER2 COLOR2
#define PMORE_COLOR_FOOTER3_KEY ""
#define PMORE_COLOR_FOOTER3_TEXT ""
#define PMORE_COLOR_FOOTER3 COLOR2
#endif // M3_USE_PMORE
// --------------------------------------------------------------- </PORTING>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
// Platform Related. NoSync is faster but if we don't have it...
// Experimental: POPULATE should work faster?
#ifdef MAP_NOSYNC
#define MF_MMAP_OPTION (MAP_NOSYNC|MAP_SHARED)
#elif defined(MAP_POPULATE)
#define MF_MMAP_OPTION (MAP_POPULATE|MAP_SHARED)
#else
#define MF_MMAP_OPTION (MAP_SHARED)
#endif
/* Developer's Guide
*
* OVERVIEW
* - pmore is designed as a line-oriented pager. After you load (mf_attach)
* a file, you can move current display window by lines (mf_forward and
* mf_backward) and then display a page(mf_display).
* And please remember to delete allocated resources (mf_detach)
* when you exit.
* - Functions are designed to work with global variables.
* However you can overcome re-entrance problem by backuping up variables
* or replace all "." to "->" with little modification and add pointer as
* argument passed to each function.
* (This is really tested and it works, however then using global variables
* is considered to be faster and easier to maintain, at lease shorter in
* time to key-in and for filelength).
* - Basically this file should only export one function, "pmore".
* Using any other functions here may be dangerous because they are not
* coded for external reentrance rightnow.
* - mf_* are operation functions to work with file buffer.
* Usually these function assumes "mf" can be accessed.
* - pmore_* are utility functions
*
* DETAIL
* - The most tricky part of pmore is the design of "maxdisps" and "maxlinenoS".
* What do they mean? "The pointer and its line number of last page".
* - Because pmore is designed to work with very large files, it's costly to
* calculate the total line numbers (and not necessary). But if we don't
* know about how many lines left can we display then when navigating by
* pages may result in a page with single line conent (if you set display
* starting pointer to the real last line).
* - To overcome this issue, maxdisps is introduced. It tries to go backward
* one page from end of file (this operation is lighter than visiting
* entire file content for line number calculation). Then we can set this
* as boundary of forward navigation.
* - maxlinenoS is the line number of maxdisps. It's NOT the real number of
* total line in current file (You have to add the last page). That's why
* it has a strange name of trailing "S", to hint you that it's not
* "maxlineno" which is easily considered as "max(total) line number".
*
* HINTS:
* - Remember mmap pointers are NOT null terminated strings.
* You have to use strn* APIs and make sure not exceeding mmap buffer.
* DO NOT USE strcmp, strstr, strchr, ...
* - Scroll handling is painful. If you displayed anything on screen,
* remember to MFDISP_DIRTY();
* - To be portable between most BBS systems, pmore is designed to
* workaround most BBS bugs inside itself.
* - Basically pmore considered the 'outc' output system as unlimited buffer.
* However on most BBS implementation, outc used a buffer with ANSILINELEN
* in length. And for some branches they even used unsigned byte for index.
* So if user complained about output truncated or blanked, increase buffer.
*/
#ifdef DEBUG
static int debug = 0;
# define MFPROTO
# define MFFPROTO
#else
# define MFPROTO static
# define MFFPROTO static
#endif
/* DBCS users tend to write unsigned char. let's make compiler happy */
#define ustrlen(x) strlen((char*)x)
#define ustrchr(x,y) (unsigned char*)strchr((char*)x, y)
#define ustrrchr(x,y) (unsigned char*)strrchr((char*)x, y)
// NOTE: this is a special strlen to speed up processing.
// WARNING: x MUST be #define x "msg".
// otherwise you need to use real strlen.
#define PMORE_MACROSTRLEN(x) (sizeof(x)-1)
// --------------------------------------------- <Defines and constants>
// --------------------------- <Display>
/* ANSI COMMAND SYSTEM */
/* On some systems with pmore style ANSI system applied,
* we don't have to define these again.
*/
#ifndef PMORE_STYLE_ANSI
#define PMORE_STYLE_ANSI
// Escapes. I don't like \033 everywhere.
#define ESC_NUM (0x1b)
#define ESC_STR "\x1b"
#define ESC_CHR '\x1b'
// Common ANSI commands.
#define ANSI_RESET ESC_STR "[m"
#define ANSI_COLOR(x) ESC_STR "[" #x "m"
#define ANSI_CLRTOEND ESC_STR "[K"
#define ANSI_MOVETO(y,x) ESC_STR "[" #y ";" #x "H"
#define ANSI_REVERSE ANSI_COLOR(7)
#define ANSI_IN_ESCAPE(x) (((x) >= '0' && (x) <= '9') || \
(x) == ';' || (x) == ',' || (x) == '[')
#endif /* PMORE_STYLE_ANSI */
#define ANSI_IN_MOVECMD(x) (strchr("ABCDfjHJRu", x) != NULL)
#define PMORE_DBCS_LEADING(c) (c >= 0x80)
// Poor BBS terminal system Workarounds
// - Most BBS implements clrtoeol() as fake command
// and usually messed up when output ANSI quoted string.
// - A workaround is suggested by kcwu:
// https://opensvn.csie.org/traccgi/pttbbs/trac.cgi/changeset/519
// - If you have problem using this workaround, define PMORE_NO_FORCE_CLRTOEOL
#ifndef PMORE_NO_FORCE_CLRTOEOL
# define FORCE_CLRTOEOL() outs(ANSI_CLRTOEND)
#else
# define FORCE_CLRTOEOL() clrtoeol()
#endif
/* Again, if you have a BBS system which optimized out* without recognizing
* ANSI escapes, scrolling with ANSI text may result in melformed text (because
* ANSI escapes were "optimized" ). So here we provide a method to overcome
* with this situation. However your should increase your I/O buffer to prevent
* flickers.
*/
MFFPROTO void
pmore_clrtoeol(int y, int x)
{
#ifdef PMORE_WORKAROUND_CLRTOEOL
int i;
move(y, x);
for (i = x; i < t_columns; i++)
outc(' ');
clrtoeol();
move(y, x); // this is required, due to outc().
#else
move(y, x);
clrtoeol();
#endif
}
MFFPROTO void
pmore_outns(const char *str, int n)
{
while (*str && n--) {
outc((unsigned char)*str++);
}
}
// --------------------------- </Display>
// --------------------------- <Main Navigation>
typedef struct
{
unsigned char
*start, *end, // file buffer
*disps, *dispe, // displayed content start/end
*maxdisps; // a very special pointer,
// consider as "disps of last page"
off_t len; // file total length
long lineno, // lineno of disps
oldlineno, // last drawn lineno, < 0 means full update
xpos, // starting x position
//
wraplines, // wrapped lines in last display
trunclines, // truncated lines in last display
dispedlines, // how many different lines displayed
// usually dispedlines = PAGE-wraplines,
// but if last line is incomplete(wrapped),
// dispedlines = PAGE-wraplines + 1
lastpagelines,// lines of last page to show
// this indicates how many lines can
// maxdisps(maxlinenoS) display.
maxlinenoS; // lineno of maxdisps, "S"!
// What does the magic "S" mean?
// Just trying to notify you that it's
// NOT REAL MAX LINENO NOR FILELENGTH!!!
// You may consider "S" of "Start" (disps).
void (*detachHandler)();
} MmappedFile;
MmappedFile mf = {
0, 0, 0, 0, 0, 0L,
0, -1L, 0, 0, -1L, -1L, -1L, -1L,
NULL // detachHandler
}; // current file
/* mf_* navigation commands return value meanings */
enum MF_NAV_COMMANDS {
MFNAV_OK, // navigation ok
MFNAV_EXCEED, // request exceeds buffer
};
/* Navigation units (dynamic, so not in enum const) */
#define MFNAV_PAGE (t_lines-2) // when navigation, how many lines in a page to move
/* Display system */
enum MF_DISP_CONST {
/* newline method (because of poor BBS implementation) */
MFDISP_NEWLINE_CLEAR = 0, // \n and cleartoeol
MFDISP_NEWLINE_SKIP,
MFDISP_NEWLINE_MOVE, // use move to simulate newline.
MFDISP_OPT_CLEAR = 0,
MFDISP_OPT_OPTIMIZED,
MFDISP_OPT_FORCEDIRTY,
// prefs
MFDISP_WRAP_TRUNCATE = 0,
MFDISP_WRAP_WRAP,
MFDISP_WRAP_MODES,
MFDISP_SEP_NONE = 0x00,
MFDISP_SEP_LINE = 0x01,
MFDISP_SEP_WRAP = 0x02,
MFDISP_SEP_OLD = MFDISP_SEP_LINE | MFDISP_SEP_WRAP,
MFDISP_SEP_MODES= 0x04,
MFDISP_RAW_NA = 0x00,
MFDISP_RAW_NOANSI,
MFDISP_RAW_PLAIN,
MFDISP_RAW_MODES,
};
#define MFDISP_PAGE (t_lines-1) // the real number of lines to be shown.
#define MFDISP_DIRTY() { mf.oldlineno = -1; }
/* Indicators */
#define MFDISP_TRUNC_INDICATOR ANSI_COLOR(0;1;37) ">" ANSI_RESET
#define MFDISP_WRAP_INDICATOR ANSI_COLOR(0;1;37) "\\" ANSI_RESET
#define MFDISP_WNAV_INDICATOR ANSI_COLOR(0;1;37) "<" ANSI_RESET
// --------------------------- </Main Navigation>
// --------------------------- <Aux. Structures>
/* browsing preference */
typedef struct
{
/* mode flags */
unsigned char
wrapmode, // wrap?
separator, // separator style
wrapindicator, // show wrap indicators
oldwrapmode, // traditional wrap
oldstatusbar, // traditional statusbar
rawmode; // show file as-is.
} MF_BrowsingPreference;
MF_BrowsingPreference bpref =
{ MFDISP_WRAP_WRAP, MFDISP_SEP_DEFAULT, 1,
0, 0, 0, };
/* structure generalized for the one-arg mf_attach_handler */
struct SimpleBuffer {
void *data;
int len;
};
/* pretty format header */
#define FH_HEADERS (4) // how many headers do we know?
#define FH_HEADER_LEN (4) // strlen of each heads
#define FH_FLOATS (2) // right floating, name and val
static const char *_fh_disp_heads[FH_HEADERS] =
{"作者", "標題", "時間", "轉信"};
typedef struct
{
int lines; // header lines
unsigned char *headers[FH_HEADERS];
unsigned char *floats [FH_FLOATS];
} MF_PrettyFormattedHeader;
MF_PrettyFormattedHeader fh = { 0, {0,0,0,0}, {0, 0}};
/* search records */
typedef struct
{
int len;
int (*cmpfunc) (const char *, const char *, size_t);
unsigned char *search_str; // maybe we can change to dynamic allocation
} MF_SearchRecord;
MF_SearchRecord sr = { 0, strncmp, NULL};
enum MFSEARCH_DIRECTION {
MFSEARCH_FORWARD,
MFSEARCH_BACKWARD,
};
// Reset structures
#define RESETMF() { memset(&mf, 0, sizeof(mf)); \
mf.lastpagelines = mf.maxlinenoS = mf.oldlineno = -1; }
#define RESETFH() { memset(&fh, 0, sizeof(fh)); \
fh.lines = -1; }
// Artwork
#define OPTATTR_NORMAL ANSI_COLOR(0;34;47)
#define OPTATTR_NORMAL_KEY ANSI_COLOR(0;31;47)
#define OPTATTR_SELECTED ANSI_COLOR(0;1;37;46)
#define OPTATTR_SELECTED_KEY ANSI_COLOR(0;31;46)
#define OPTATTR_BAR ANSI_COLOR(0;1;30;47)
#define PREFATTR_NORMAL ANSI_COLOR(0)
#define PREFATTR_NORMAL_KEY ANSI_COLOR(0;1;31)
#define PREFATTR_SELECTED ANSI_COLOR(0;1;36)
#define PREFATTR_SELECTED_KEY ANSI_COLOR(0;1;31)
#define PREFATTR_BAR ANSI_COLOR(0;1;30)
#define PMHLPATTR_NORMAL ANSI_COLOR(0)
#define PMHLPATTR_NORMAL_KEY ANSI_COLOR(0;1;36)
#define PMHLPATTR_HEADER ANSI_COLOR(0;1;32)
// Prompt Bar Shadow
#define PMORE_SHADOW_ABOVE (1)
#define PMORE_SHADOW_BELOW (2)
#define PMORE_SHADOW_NONE (0)
// --------------------------- </Aux. Structures>
// --------------------------------------------- </Defines and constants>
// --------------------------------------------- <Optional Modules>
#if defined(PMORE_EXPAND_ESC_STAR) && !defined(HAVE_EXPAND_ESC_STAR)
//
// support TWBBS ESC*s style variables.
// if return value > 1, pmore will show warning message.
//
// This is a sample expand_esc_star() function.
// If your system supports more variables, please write
// your own version outside pmore.c, and define in config.h:
//
// #define HAVE_EXPAND_ESC_STAR
//
int
expand_esc_star(char *buf, const char *src, int szbuf)
{
assert(*src == KEY_ESC && *(src+1) == '*');
src += 2;
switch (*src) {
// secure content (return 1)
case 't': // current time.
strlcpy(buf, Now(), szbuf);
return 1;
// insecure content (return 2)
case 's': // current user id
strlcpy(buf, cuser.userid, szbuf);
return 2;
case 'l': // current user logins
snprintf(buf, szbuf, "%d", cuser.numlogins);
return 2;
case 'p': // current user posts
snprintf(buf, szbuf, "%d", cuser.numposts);
return 2;
}
// unknown characters, return from star.
strlcpy(buf, src-1, szbuf);
return 0;
}
#endif // defined(PMORE_EXPAND_ESC_STAR) && !defined(HAVE_EXPAND_ESC_STAR)
#ifdef PMORE_USE_ASCII_MOVIE
enum _MFDISP_MOVIE_MODES {
MFDISP_MOVIE_UNKNOWN= 0,
MFDISP_MOVIE_DETECTED,
MFDISP_MOVIE_YES,
MFDISP_MOVIE_NO,
MFDISP_MOVIE_PLAYING,
MFDISP_MOVIE_PLAYING_OLD,
};
typedef struct {
struct timeval frameclk;
struct timeval synctime;
unsigned char *options,
*optkeys;
unsigned char *intr_src;
unsigned int intr_dest_frame;
unsigned char mode,
compat24,
interactive,
pause;
unsigned char *lastframe;
} MF_Movie;
MF_Movie mfmovie;
#define STOP_MOVIE() { \
mfmovie.options = NULL; \
mfmovie.pause = 0; \
if (mfmovie.mode == MFDISP_MOVIE_PLAYING) \
mfmovie.mode = MFDISP_MOVIE_YES; \
if (mfmovie.mode == MFDISP_MOVIE_PLAYING_OLD) \
mfmovie.mode = MFDISP_MOVIE_NO; \
mf_determinemaxdisps(MFNAV_PAGE, 0); \
mf_forward(0); \
}
#define RESET_MOVIE() { \
mfmovie.mode = MFDISP_MOVIE_UNKNOWN; \
mfmovie.options = NULL; \
mfmovie.optkeys = NULL; \
mfmovie.intr_src= NULL; \
mfmovie.intr_dest_frame = 0; \
mfmovie.compat24 = 1; \
mfmovie.pause = 0; \
mfmovie.interactive = 0; \
mfmovie.synctime.tv_sec = mfmovie.synctime.tv_usec = 0; \
mfmovie.frameclk.tv_sec = 1; mfmovie.frameclk.tv_usec = 0; \
mfmovie.lastframe = NULL; \
}
#define MOVIE_IS_PLAYING() \
((mfmovie.mode == MFDISP_MOVIE_PLAYING) || \
(mfmovie.mode == MFDISP_MOVIE_PLAYING_OLD))
unsigned char *
mf_movieFrameHeader(unsigned char *p, unsigned char *end);
void mf_float2tv(float f, struct timeval *ptv);
MFPROTO int mf_movieWaitKey(struct timeval *ptv, int dorefresh);
MFPROTO int mf_movieNextFrame();
MFPROTO int mf_movieSyncFrame();
MFPROTO int mf_moviePromptPlaying(int type);
MFPROTO unsigned char *mf_movieNextLine();
MFFPROTO int mf_movieMaskedInput(int c);
#define MOVIE_MIN_FRAMECLK (0.1f)
#define MOVIE_MAX_FRAMECLK (3600.0f)
#define MOVIE_SECOND_U (1000000L)
#define MOVIE_ANTI_ANTI_IDLE
// some magic value that your vkey() will never return
#define MOVIE_KEY_ANY (0x4d464b41)
#define MOVIE_KEY_NONE (0x414b464d)
// some environments already converted 0x7F to 0x08,
// but we'd still do it again here for compatibility.
#ifndef MOVIE_KEY_BS2
#define MOVIE_KEY_BS2 (0x7f)
#endif
#endif
// --------------------------------------------- </Optional Modules>
// used by mf_attach
MFPROTO void mf_parseHeaders();
MFPROTO void mf_freeHeaders();
MFPROTO void mf_determinemaxdisps(int, int);
#ifdef PMORE_GUNZIP_CMD
#include <sys/wait.h>
MFPROTO int
mf_gunzip(const char *fn GCC_UNUSED, int fd)
{
char magic[2] = {0};
const char gzip_magic[2] = {0x1f, 0x8b};
FILE *tmp;
int tmp_fd, sts = 0;
// quick abort if fd is invalid
if (fd < 0)
return fd;
// TODO since most files were not gzipped, maybe we can
// move type checking to "after mmap attached"
if (read(fd, magic, sizeof(magic)) != sizeof(magic) ||
memcmp(gzip_magic, magic, sizeof(magic)) != 0) {
// XXX since we only use 'mmap' in pmore, no need to rewind fd
return fd;
}
// create temp file
tmp = tmpfile();
assert(tmp);
tmp_fd = dup(fileno(tmp));
assert(tmp_fd > 0);
fclose(tmp);
// rewind for decompression
lseek(fd, 0, SEEK_SET);
switch (fork()) {
case 0:
// child
dup2(fd, 0); // input
dup2(tmp_fd, 1); // output
dup2(tmp_fd, 2); // err
// sample: gunzip -d -c
exit(system(PMORE_GUNZIP_CMD));
break;
case -1:
// error
close(tmp_fd);
return fd;
default:
// parent
wait(&sts); // since file is gzipped, tmp gives error if failed.
break;
}
close(fd);
return tmp_fd;
}
#endif
/*
* mmap basic operations
*/
MFPROTO void mf_detach();
MFPROTO void mf_detach_nounmap();
MFPROTO int mf_postattach();
MFPROTO int
mf_attach_file(void *fnptr)
{
// We are passing pointer
const char *fn = *(const char **)fnptr;
struct stat st;
int fd = open(fn, O_RDONLY);
#ifdef PMORE_GUNZIP_CMD
fd = mf_gunzip(fn, fd);
#endif
if (fd < 0)
return 0;
if (fstat(fd, &st) || ((mf.len = st.st_size) <= 0) || S_ISDIR(st.st_mode)) {
mf.len = 0;
close(fd);
return 0;
}
/*
mf.len = lseek(fd, 0L, SEEK_END);
lseek(fd, 0, SEEK_SET);
*/
mf.start = mmap(NULL, mf.len, PROT_READ, MF_MMAP_OPTION, fd, 0);
close(fd);
if (mf.start == MAP_FAILED) {
RESETMF();
return 0;
}
#ifdef MADV_SEQUENTIAL
// BSD mmap advise. comment if your OS does not support this.
madvise(mf.start, mf.len, MADV_SEQUENTIAL);
#endif
mf.detachHandler = mf_detach;
return mf_postattach();
}
MFPROTO int
mf_attach_buffer(void *buf)
{
struct SimpleBuffer *buffer = (struct SimpleBuffer *)buf;
if (!buffer || !buffer->data || !buffer->len)
return 0;
mf.start = buffer->data;
mf.len = buffer->len;
mf.detachHandler = mf_detach_nounmap;
return mf_postattach();
}
MFPROTO int
mf_postattach()
{
mf.end = mf.start + mf.len;
mf.disps = mf.dispe = mf.start;
mf.lineno = 0;
mf_determinemaxdisps(MFNAV_PAGE, 0);
mf.disps = mf.dispe = mf.start;
mf.lineno = 0;
/* reset and parse article header */
mf_parseHeaders();
/* a workaround for wrapped separators */
if (mf.maxlinenoS > 0 &&
fh.lines >= mf.maxlinenoS &&
bpref.separator & MFDISP_SEP_WRAP) {
mf_determinemaxdisps(+1, 1);
}
return 1;
}
MFPROTO void
mf_detach()
{
mf_freeHeaders();
if (mf.start) {
munmap(mf.start, mf.len);
RESETMF();
}
}
MFPROTO void
mf_detach_nounmap()
{
mf_freeHeaders();
if (mf.start)
RESETMF();
}
/*
* lineno calculation, and moving
*/
MFFPROTO void
mf_sync_lineno()
{
unsigned char *p;
if (mf.disps == mf.maxdisps && mf.maxlinenoS >= 0) {
mf.lineno = mf.maxlinenoS;
} else {
mf.lineno = 0;
for (p = mf.start; p < mf.disps; p++)
if (*p == '\n')
mf.lineno ++;
if (mf.disps == mf.maxdisps && mf.maxlinenoS < 0)
mf.maxlinenoS = mf.lineno;
}
}
MFPROTO int mf_backward(int); // used by mf_buildmaxdisps
MFPROTO int mf_forward(int); // used by mf_buildmaxdisps
MFPROTO void
mf_determinemaxdisps(int backlines, int update_by_offset)
{
unsigned char *pbak = mf.disps, *mbak = mf.maxdisps;
long lbak = mf.lineno;
if (update_by_offset) {
if (backlines > 0) {
/* tricky way because usually
* mf_forward checks maxdisps.
*/
mf.disps = mf.maxdisps;
mf.maxdisps = mf.end-1;
mf_forward(backlines);
mf_backward(0);
} else
mf_backward(backlines);
} else {
mf.lineno = backlines;
mf.disps = mf.end - 1;
backlines = mf_backward(backlines);
}
if (mf.disps != mbak) {
mf.maxdisps = mf.disps;
if (update_by_offset)
mf.lastpagelines -= backlines;
else
mf.lastpagelines = backlines;
mf.maxlinenoS = -1;
#ifdef PMORE_PRELOAD_SIZE
if (mf.len <= PMORE_PRELOAD_SIZE)
mf_sync_lineno(); // maxlinenoS will be automatically updated
#endif
}
mf.disps = pbak;
mf.lineno = lbak;
}
/*
* mf_backwards is also used for maxno determination,
* so we cannot change anything in mf except these:
* mf.disps
* mf.lineno
*/
MFPROTO int
mf_backward(int lines)
{
int real_moved = 0;