-
Notifications
You must be signed in to change notification settings - Fork 0
/
intramine_viewer.pl
3343 lines (2988 loc) · 112 KB
/
intramine_viewer.pl
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
# intramine_viewer.pl: use CodeMirror to display most code files,
# with custom display (code below) for txt, Perl, and pod.
# Pdf and docx also have basic viewers.
# All code and text files have autolinks, and image hovers, and glossary popups.
# Text files (.txt) are given the full Gloss (like Markdown) treatment with
# headings, lists, tables, autolinks, image hovers, special characters,
# horizontal rules and a table of contents on the left.
# Files with tables of contents: txt, pl, pm, pod, C(++), js, css, go,
# and many others supported by ctags such as PHP, Ruby - see libs/toc_local.pm and ex_ctags.pm.
# This is not a "top" server, meaning it doesn't have an entry in IntraMine's top navigation bar.
# Typically it's called by click on a link in Search page results, the Files page lists,
# or a link in a view provided by this Viewer or the Editor service.
# perl C:\perlprogs\IntraMine\intramine_viewer.pl
use strict;
use warnings;
use utf8;
use FileHandle;
use Encode;
use Encode::Guess;
use HTML::Entities;
use URI::Escape;
use Text::Tabs;
$tabstop = 4;
use Syntax::Highlight::Perl::Improved ':BASIC'; # ':BASIC' or ':FULL' - FULL doesn't seem to do much
use Time::HiRes qw ( time );
use Win32::Process 'STILL_ACTIVE'; # for calling Universal ctags.exe etc
#use Win32::Process; # for calling Universal ctags.exe etc
use JSON::MaybeXS qw(encode_json);
use Text::MultiMarkdown; # for .md files
use Path::Tiny qw(path);
use Pod::Simple::HTML;
use lib path($0)->absolute->parent->child('libs')->stringify;
use common;
use swarmserver;
use win_wide_filepaths;
use win_user32_local;
use docx2txt;
use ext; # for ext.pm#IsTextExtensionNoPeriod() etc.
use html2gloss;
use toc_local;
#use cobol_keywords;
Encode::Guess->add_suspects(qw/iso-8859-1/);
$| = 1;
# Some ASCII values, used in AddInternalLinksToPerlLine().
my $ORD_a = ord('a');
my $ORD_z = ord('z');
my $ORD_A = ord('A');
my $ORD_Z = ord('Z');
my $ORD_0 = ord('0');
my $ORD_9 = ord('9');
# Circled letters, used in tables of contents.
my $C_icon = '<span class="circle_green">C</span>'; # Class
my $S_icon = '<span class="circle_green">S</span>'; # Struct
my $M_icon = '<span class="circle_green">M</span>'; # Module
my $T_icon = '<span class="circle_blue">T</span>'; # Type
my $D_icon = '<span class="circle_blue">D</span>'; # Data
my $m_icon = '<span class="circle_red">m</span>'; # method
my $f_icon = '<span class="circle_red">f</span>'; # function
my $s_icon = '<span class="circle_red">s</span>'; # subroutine
my %VideMimeTypeForExtension;
$VideMimeTypeForExtension{'mp4'} = 'video/mp4';
$VideMimeTypeForExtension{'m4v'} = 'video/MP4V-ES';
$VideMimeTypeForExtension{'webm'} = 'video/webm';
$VideMimeTypeForExtension{'3gp'} = 'video/3gpp';
$VideMimeTypeForExtension{'mkv'} = 'video/x-matroska';
$VideMimeTypeForExtension{'avi'} = 'video/x-msvideo';
$VideMimeTypeForExtension{'mpeg'} = 'video/mpeg';
$VideMimeTypeForExtension{'ogv'} = 'video/ogg';
$VideMimeTypeForExtension{'ts'} = 'video/mp2t';
$VideMimeTypeForExtension{'3g2'} = 'video/3gpp2';
$VideMimeTypeForExtension{'ogg'} = 'application/ogg';
#LoadCobolKeywords();
my $PAGENAME = '';
my $SHORTNAME = '';
my $server_port = '';
my $port_listen = '';
SSInitialize(\$PAGENAME, \$SHORTNAME, \$server_port, \$port_listen);
my $IMAGES_DIR = FullDirectoryPath('IMAGES_DIR');
#my $COMMON_IMAGES_DIR = CVal('COMMON_IMAGES_DIR');
my $UseAppForLocalEditing = CVal('USE_APP_FOR_EDITING');
my $UseAppForRemoteEditing = CVal('USE_APP_FOR_REMOTE_EDITING');
my $AllowLocalEditing = CVal('ALLOW_LOCAL_EDITING');
my $AllowRemoteEditing = CVal('ALLOW_REMOTE_EDITING');
# Just a whimsy - for contents.txt files that start with CONTENTS, try to make it look
# like an old-fashioned "special" table of contents. Initialized here.
InitSpecialIndexFileHandling();
my $kLOGMESSAGES = 0; # 1 == Log Output() messages
my $kDISPLAYMESSAGES = 0; # 1 == print messages from Output() to console window
# Log is at logs/IntraMine/$SHORTNAME $port_listen datestamp.txt in the IntraMine folder.
# Use the Output() sub for routine log/print.
StartNewLog($kLOGMESSAGES, $kDISPLAYMESSAGES);
my $GLOSSARYFILENAME = lc(CVal('GLOSSARYFILENAME'));
# For ATX-style headings that start with a '#', optionally require blank line before
# (which is the default).
my $HashHeadingRequireBlankBefore = CVal("HASH_HEADING_NEEDS_BLANK_BEFORE");
InitPerlSyntaxHighlighter();
my $LogDir = FullDirectoryPath('LogDir');
my $ctags_dir = CVal('CTAGS_DIR');
InitTocLocal($LogDir . 'temp/tempctags', $port_listen, $LogDir, $ctags_dir, $HashHeadingRequireBlankBefore);
#InitCtags($LogDir . 'temp/tempctags');
Output("Starting $SHORTNAME on port $port_listen\n\n");
# This service has no default action. For file display either 'href=path'
# or the more RESTful '.../file/path' can be used. See eg intramine_search.js#viewerOpenAnchor()
# (a call to that is inserted by elasticsearcher.pm#FormatHitResults() among others).
my %RequestAction;
$RequestAction{'href'} = \&FullFile; # Open file, href = anything
$RequestAction{'/file/'} = \&FullFile; # RESTful alternative, /file/is followed by file path in $obj
$RequestAction{'req|loadfile'} = \&LoadTheFile; # req=loadfile
$RequestAction{'req|openDirectory'} = \&OpenDirectory; # req=openDirectory
# The following two callbacks are needed if any css/js files
# are passed to GetStandardPageLoader() in the first argument. Not needed here.
$RequestAction{'req|css'} = \&GetRequestedFile; # req=css see swarmserver.pm#GetRequestedFile()
$RequestAction{'req|js'} = \&GetRequestedFile; # req=js
# Testing
$RequestAction{'/test/'} = \&SelfTest; # Ask this server to test itself.
# Not needed, done in swarmserver: $RequestAction{'req|id'} = \&Identify; # req=id
MainLoop(\%RequestAction);
################### subs
# A browser view of a file. Text, source (226 extensions currently), PDF, HTML, Word.
# Most views are created using CodeMirror.
# pl, pm, pod, txt, log, bat, cgi, and t extensions have "custom" views generated below, rather
# than using CodeMirror.
# A serious attempt has been made to give CodeMirror and custom views the same capabilities,
# even though the two approaches differ greatly. The difference is due mainly to the use by
# CodeMirror of "overlays" for anything custom - so for example, a link or highlight in a
# CodeMirror view needs an overlay marker to put the link or highlight "on top" of the text.
# See eg https://codemirror.net/doc/manual.html#markText.
# In the custom views, the link is inserted directly into the displayed HTML.
# Because creating overlay markers for all links in a large file is moderately expensive,
# the markers are created on demand, when new lines are scrolled into view.
# The real work is done by GetContentBasedOnExtension() below.
# 2020-02-28 15_55_57-reverse_filepaths.pm.png
sub FullFile {
my ($obj, $formH, $peeraddress) = @_;
my $theBody = FullFileTemplate();
my $t1 = time;
my $fileServerPort = $port_listen;
my $usingRESTfulApproach = 0;
$formH->{'FULLPATH'} = '';
# Accept argument based 'href=filepath' in $formH or more RESTful /file/path in $obj.
if (!defined($formH->{'href'}))
{
$usingRESTfulApproach = 1;
if ($obj =~ m!$SHORTNAME/file/([^\?]+)!)
{
my $path = $1;
$path =~ s!/$!!;
$formH->{'FULLPATH'} = $path;
}
}
if (defined($formH->{'href'}))
{
$formH->{'FULLPATH'} = $formH->{'href'};
}
my $filePath = $formH->{'FULLPATH'};
# Revision (temporarily at least), return '' if file does not exist. This leads to an ugly
# 404 generated by the browser, but it's all I've got at the moment. The problem is with
# JS-generated paths such as
# C:/perlprogs/mine/test/mode/clike/clike.js
# which is a blend of eg C:\perlprogs\mine\test\googlesuggest.cpp (the main file)
# and mode/clike/clike.js (a CodeMirror subfolder). Since the JS-generated path looks like
# and could in fact be a real path, we have to reject it if the file is not found.
# The rub there is that if C:/perlprogs/mine/test/mode/clike/clike.js does in fact
# exist then the load is toast, the wrong clike.js will be loaded. This problem happens
# only for RESTful URLs, arg-based is fine.
if ($usingRESTfulApproach && FileOrDirExistsWide($filePath) != 1)
{
# TEST ONLY codathon
print("FullFile REJECTED |$filePath|\n");
return('');
}
# Early return if file does not exist and it's not a bogus request from the browser.
# if (FileOrDirExistsWide($filePath) != 1)
# {
# # For RESTful (eg /file/path/goodfile.txt) requests, browser often asks for css and js using path
# # /file/path/goodfile.txt/this/that/afile.css. In this case, we should immediately return '', signalling
# # to the caller (typically swarmserver.pm#HandleRequestAction()) that it was a bad request
# # and caller should keep trying (eg call swarmserver.pm#GetCssResult()).
# # Otherwise, if "$preFileName" does not exist on disk, we assume the $filePath really is bad
# # and return a nice result page with nav bar etc saying NOT RETRIEVED.
# print("Considering \$filePath |$filePath|\n");
#
# # Sometimes we need to strip off more than one part of the path to reveal the original
# # path, eg .../test/googlesuggest.cpp/addon/dialog/dialog.css
# my $filePathCopy = $filePath;
# my $fnPosition = rindex($filePathCopy, '/');
#
# while ($fnPosition > 3)
# {
# $filePathCopy = substr($filePathCopy, 0, $fnPosition);
# if ($filePathCopy =~ m!\.\w+$!)
# {
# if (FileOrDirExistsWide($filePathCopy) == 1)
# {
# print("BOGUS CALL, returning ''.\n");
# return('');
# }
# else
# {
# last; # Check once only if an extension is seen.
# }
# }
# $fnPosition = rindex($filePathCopy, '/');
# }
# }
my $title = $filePath . ' NOT RETRIEVED!';
my $serverAddr = ServerAddress();
my $clientIsRemote = 0;
# If client is on the server then peeraddress can be either 127.0.0.1 or $serverAddr:
# if client is NOT on the server then peeraddress is not 127.0.0.1 and differs from $serverAddr.
if ($peeraddress ne '127.0.0.1' && $peeraddress ne $serverAddr) #if ($peeraddress ne $serverAddr)
#if ($peeraddress ne '127.0.0.1')
{
$clientIsRemote = 1;
}
my $allowEditing = (($clientIsRemote && $AllowRemoteEditing) || (!$clientIsRemote && $AllowLocalEditing));
my $useAppForEditing = 0;
if ($allowEditing)
{
$useAppForEditing = (($clientIsRemote && $UseAppForRemoteEditing) || (!$clientIsRemote && $UseAppForLocalEditing));
}
# Editing can be done with IntraMine's Editor, or with your preferred text editor.
# See intramine_config.txt "ALLOW_LOCAL_EDITING" et seq for some notes on setting up
# local editing (on the IntraMine box) and remote editing. You can use IntraMine or your
# preferred app locally or remotely, or disable editing for either.
my $amRemoteValue = $clientIsRemote ? 'true' : 'false';
my $tfAllowEditing = ($allowEditing) ? 'true' : 'false';
my $tfUseAppForEditing = ($useAppForEditing) ? 'true' : 'false';
my $host = $serverAddr;
my $port = $port_listen;
my $fileContents = '<p>Read error!</p>';
my $meta = "";
my $customCSS = '';
my $textTableCSS = '';
# For cmTextHolderName = '_CMTEXTHOLDERNAME_'; -- can also be 'scrollTextRightOfContents'
my $textHolderName = 'scrollText';
my $usingCM = 'true'; # for _USING_CM_ etc (using CodeMirror)
my $ctrlSPath = $filePath;
my $topNav = TopNav($PAGENAME);
$theBody =~ s!_TOPNAV_!$topNav!;
my $exists = FileOrDirExistsWide($filePath);
if ($exists == 1)
{
$title = $filePath;
$ctrlSPath = encode_utf8($ctrlSPath);
$ctrlSPath =~ s!%!%25!g;
$ctrlSPath =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
# Added Feb 2024, if it's a video throw it up in a new browser tab.
if (EndsWithVideoExtension($filePath))
{
ShowVideo($obj, $formH, $peeraddress, $clientIsRemote);
return("1");
}
# Categories: see GetContentBasedOnExtension() below. Here we handle HTML.
# 1.1
# If a local HTML file has been requested, skip the TopNav() etc and just return the page as-is.
# DEFAULTDIR is needed for serving up css and js files associated with the page, when url for
# the resource starts with "./".
# This is the "view" for HTML: "edit" shows the raw HTML as text.
if ($filePath =~ m!\.html?$!i)
{
GetHTML($formH, $peeraddress, \$fileContents);
# $meta not needed.
my $dir = lc(DirectoryFromPathTS($filePath));
$formH->{'DEFAULTDIR'} = $dir;
return($fileContents);
}
else # all other categories of extension
{
GetContentBasedOnExtension($formH, $peeraddress, $filePath,
$clientIsRemote, $allowEditing, \$fileContents,
\$usingCM, \$meta, \$textTableCSS, \$customCSS,
\$textHolderName);
}
}
else
{
# Fail, use text JS and CSS for the 404 display.
$usingCM = 'false';
$customCSS = '<link rel="stylesheet" type="text/css" href="non_cm_text.css" />';
}
# Remove scrollAdjustedHeight if it's an image.
# And take out the toggle button.
if ($filePath =~ m!\.(png|gif|jpe?g|ico|webp)$!i)
{
$theBody =~ s! id='scrollAdjustedHeight'!!;
$theBody =~ s!_TOGGLEPOSACTION_!!;
}
# Insert the HTML to load various JavaScript and CSS files as needed. Plus the "meta" line.
$theBody =~ s!_META_CHARSET_!$meta!;
$theBody =~ s!_CSS_!$customCSS!;
$theBody =~ s!_TEXTTABLECSS_!$textTableCSS!;
my $customJS = ($usingCM eq 'true') ? CodeMirrorJS() : NonCodeMirrorJS();
# Add lolight JS for .txt files only.
if ($filePath =~ m!\.txt$!)
{
$customJS .= "\n" . '<script src="lolight-1.4.0.min.js"></script>';
}
$theBody =~ s!_JAVASCRIPT_!$customJS!;
# Full path is unhelpful in the <title>, trim down to just file name.
my $fileName = FileNameFromPath($title);
$fileName = &HTML::Entities::encode($fileName);
$theBody =~ s!_TITLE_!$fileName!;
# Make a copy of title, just for console display.
my $consoleDisplayedTitle = $title;
# Flip the slashes for file path in _TITLEHEADER_ at top of the page, for easier
# copy/paste into notepad++ etc.
$title =~ s!/!\\!g;
$title = &HTML::Entities::encode($title);
# Grab mod date and file size.
my $modDate = GetFileModTimeWide($filePath);
my $size = GetFileSizeWide($filePath);
my $sizeDateStr = DateSizeString($modDate, $size);
# Fill in the placeholders in the HTML template for title etc. And give values to
# JS variables. See FullFileTemplate() just below.
$theBody =~ s!_TITLEHEADER_!$title!;
$theBody =~ s!_DATEANDSIZE_!$sizeDateStr!;
# Use $ctrlSPath for $filePath beyond this point.
# Why? It works. Otherwise Unicode is messed up.
$filePath = $ctrlSPath;
$theBody =~ s!_PATH_!$filePath!g;
$theBody =~ s!_ENCODEDPATH_!$ctrlSPath!g;
$theBody =~ s!_USING_CM_!$usingCM!;
$theBody =~ s!_CMTEXTHOLDERNAME_!$textHolderName!g;
my $findTip = ''; #"(Unshift for lower case)"; I have forgotten why I did that
$theBody =~ s!_MESSAGE__!$findTip!;
#####$theBody =~ s!_THEHOST_!$host!g;
$theBody =~ s!_THEPORT_!$port!g;
$theBody =~ s!_PEERADDRESS_!$peeraddress!g;
#####$theBody =~ s!_THEMAINPORT_!$server_port!;
$theBody =~ s!_CLIENT_IP_ADDRESS_!$peeraddress!;
#####$theBody =~ s!_SHORTSERVERNAME_!$SHORTNAME!;
my $viewerShortName = CVal('VIEWERSHORTNAME');
my $openerShortName = CVal('OPENERSHORTNAME');
my $editorShortName = CVal('EDITORSHORTNAME');
my $linkerShortName = CVal('LINKERSHORTNAME');
my $filesShortName = CVal('FILESSHORTNAME');
my $videoShortName = CVal('VIDEOSHORTNAME');
$theBody =~ s!_VIEWERSHORTNAME_!$viewerShortName!;
$theBody =~ s!_OPENERSHORTNAME_!$openerShortName!;
$theBody =~ s!_EDITORSHORTNAME_!$editorShortName!;
$theBody =~ s!_LINKERSHORTNAME_!$linkerShortName!;
$theBody =~ s!_FILESSHORTNAME_!$filesShortName!;
$theBody =~ s!_VIDEOSHORTNAME_!$videoShortName!;
#$theBody =~ s!_FILESERVERPORT_!$fileServerPort!g;
$theBody =~ s!_WEAREREMOTE_!$amRemoteValue!;
$theBody =~ s!_ALLOW_EDITING_!$tfAllowEditing!;
$theBody =~ s!_USE_APP_FOR_EDITING_!$tfUseAppForEditing!;
my $dtime = DoubleClickTime();
$theBody =~ s!_DOUBLECLICKTIME_!$dtime!;
# Put in an "Edit" button for files that can be edited (if editing is allowed).
# "Edit" can invoke IntraMine's Editor or your preferred editor.
my $editAction = EditButton($host, $filePath, $clientIsRemote, $allowEditing);
$theBody =~ s!_EDITACTION_!$editAction!;
# Experimental, trying to add Search/Find.
my $search = "<input id=\"search-button\" class=\"submit-button\" type=\"submit\" value=\"Find\" />";
$theBody =~ s!_SEARCH_!$search!;
# Detect any searchItems passed along for hilighting. If there are any, add a
# "Hide/Show Initial Hits" button at top of page.
my $searchItems = defined($formH->{'searchItems'}) ? $formH->{'searchItems'} : '';
my ($highlightItems, $toggleHitsButton) = InitialHighlightItems($formH, $usingCM, $searchItems);
$theBody =~ s!_HIGHLIGHTITEMS_!$highlightItems!;
$theBody =~ s!_INITIALHITSACTION_!$toggleHitsButton!;
my $togglePositionButton = '';
# Mardown Toggle won't work because there are no line numbers.
if ($filePath !~ m!\.md$!i)
{
$togglePositionButton = PositionToggle();
}
$theBody =~ s!_TOGGLEPOSACTION_!$togglePositionButton!;
my $inlineHoverButton = InlineHoverButton($filePath);
$theBody =~ s!_HOVERINLINE_!$inlineHoverButton!;
# Hilight class for table of contents selected element - see also non_cm_test.css
# and cm_viewer.css.
$theBody =~ s!_SELECTEDTOCID_!tocitup!;
# Put in main IP, main port, our short name for JavaScript.
PutPortsAndShortnameAtEndOfBody(\$theBody); # swarmserver.pm#PutPortsAndShortnameAtEndOfBody()
# Keep this last, else a casual mention of _TITLE_ etc in the file contents
# could get replaced by one of the above substitutions.
$theBody =~ s!_FILECONTENTS_!$fileContents!;
my $elapsed = time - $t1;
my $ruffElapsed = substr($elapsed, 0, 6);
#Output("Full File load time for $consoleDisplayedTitle: $ruffElapsed seconds\n");
# TEST ONLY display load time.
#print("Full File load time for $consoleDisplayedTitle: $ruffElapsed seconds\n");
return $theBody;
}
# HTML "skeleton" for the view. Placeholders (all caps with underscores) are filled in
# above in FullFile().
sub FullFileTemplate {
my $theBody = <<'FINIS';
<!doctype html>
<html lang="en">
<head>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-touch-fullscreen" content="yes" />
<meta name="google" content="notranslate">
_META_CHARSET_
<!-- <meta http-equiv="content-type" content="text/plain; charset=utf-8"> -->
<title>_TITLE_</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="forms.css" />
_CSS_
_TEXTTABLECSS_
<link rel="stylesheet" type="text/css" href="tooltip.css" />
<link rel="stylesheet" type="text/css" href="dragTOC.css" />
</head>
<body>
<!-- added for touch scrolling, an indicator -->
<div id="indicator"></div> <!-- iPad -->
<div id="indicatorPC"></div>
_TOPNAV_
<div id="title-block">
<span id="viewEditTitle">_TITLEHEADER_</span><br /><span id="viewEditDateSize">_DATEANDSIZE_</span>
</div>
<div id="button-block">
_EDITACTION_ _INITIALHITSACTION_ _TOGGLEPOSACTION_ _SEARCH_ _HOVERINLINE_<span id="editor_error"> </span> <span id='small-tip'>_MESSAGE__</span>
</div>
<hr id="rule_above_editor" />
<div id='scrollAdjustedHeight'>
_FILECONTENTS_
</div>
<script>
let weAreRemote = _WEAREREMOTE_;
let allowEditing = _ALLOW_EDITING_;
let useAppForEditing = _USE_APP_FOR_EDITING_;
let thePath = '_PATH_';
let theEncodedPath = '_ENCODEDPATH_';
let usingCM = _USING_CM_;
let cmTextHolderName = '_CMTEXTHOLDERNAME_';
let specialTextHolderName = 'specialScrollTextRightOfContents';
let clientIPAddress = '_CLIENT_IP_ADDRESS_'; // ip address of client (dup, for Editing only)
let ourServerPort = '_THEPORT_';
let viewerShortName = '_VIEWERSHORTNAME_';
let openerShortName = '_OPENERSHORTNAME_';
let editorShortName = '_EDITORSHORTNAME_';
let linkerShortName = '_LINKERSHORTNAME_';
let filesShortName = '_FILESSHORTNAME_';
let videoShortName = '_VIDEOSHORTNAME_';
let peeraddress = '_PEERADDRESS_'; // ip address of client
let errorID = "editor_error";
let highlightItems = [_HIGHLIGHTITEMS_];
let b64ToggleImage = '';
let selectedTocId = '_SELECTEDTOCID_';
let doubleClickTime = _DOUBLECLICKTIME_;
let weAreEditing = false; // Don't adjust user selection if editing - we are not editing here.
</script>
<script>
// Call fn when ready.
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
<script src="debounce.js"></script>
<script src="tooltip.js"></script>
_JAVASCRIPT_
<script>
window.addEventListener('wsinit', function (e) { wsSendMessage('activity ' + shortServerName + ' ' + ourSSListeningPort); }, false);
</script>
</body></html>
FINIS
return($theBody);
}
# Fill in contents, meta line, and css file names based on extension at end of $filepath.
# Categories:
# 1. not text: PDF, docx, html (for viewing purposes), images.
# 2. pure custom with Table Of Contents (TOC): pl, pm, pod, txt, log, bat, cgi, y.
# 2.1 custom, no TOC: md (Markdown).
# 3.1 CodeMirror (CM) with TOC, no ctag support: go.
# 3.2 CM with TOC, ctag support: cpp, js, etc.
# 4. CM, no TOC: textile, out, other uncommon formats not supported by ctags.
# Note HTML is done above (Category 1.1).
sub GetContentBasedOnExtension {
my ($formH, $peeraddress, $filePath,
$clientIsRemote, $allowEditing, $fileContents_R,
$usingCM_R, $meta_R, $textTableCSS_R, $customCSS_R,
$textHolderName_R) = @_;
# CSS varies: CodeMirror, Markdown, (other) non-CodeMirror.
# CodeMirror CSS:
my $cssForCM =
'<link rel="stylesheet" type="text/css" href="lib/codemirror.css" />' . "\n" .
'<link rel="stylesheet" type="text/css" href="addon/dialog/dialog.css" />' . "\n" .
'<link rel="stylesheet" type="text/css" href="addon/search/matchesonscrollbar.css" />' . "\n" .
'<link rel="stylesheet" type="text/css" media="screen" href="addon/search/cm_small_tip.css" />' . "\n" .
'<link rel="stylesheet" type="text/css" href="cm_viewer.css" />' . "\n";
# Markdown CSS:
my $cssForMD = '<link rel="stylesheet" type="text/css" href="cm_md.css" />';
# Non CodeMirror CSS:
my $cssForNonCm = '<link rel="stylesheet" type="text/css" href="non_cm_text.css" />';
# For $textTableCSS variations, some table formatting.
my $cssForNonCmTables = '<link rel="stylesheet" type="text/css" href="non_cm_tables.css" />';
my $cssForPod = '<link rel="stylesheet" type="text/css" href="pod.css" />';
# 1.2 Images: entire "contents" of the page is just an img link.
if ($filePath =~ m!\.(png|gif|jpe?g|ico|webp)$!i)
{
# Temp, using $port_listen instead of $server_port to open images.
# I'm working on it. Actually, no, I'm just leaving it.
GetImageLink($formH, $peeraddress, $port_listen, $fileContents_R);
$$usingCM_R = 'false';
# $metaR is not needed.
}
# 1.3 PDF
elsif ($filePath =~ m!\.pdf$!i)
{
GetPDF($formH, $peeraddress, $fileContents_R);
$$usingCM_R = 'false';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
}
elsif ($filePath =~ m!\.docx$!i) # old ".doc" is not supported
{
GetWordAsText($formH, $peeraddress, $fileContents_R);
$$usingCM_R = 'false';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=windows-1252">';
$$textTableCSS_R = $cssForNonCmTables;
$$customCSS_R = $cssForNonCm;
}
# 2. pure custom with TOC: pl, pm, pod, txt, log, bat, cgi, t.
elsif ($filePath =~ m!\.(p[lm]|cgi|t)$!i)
{
GetPrettyPerlFileContents($formH, $peeraddress, $clientIsRemote, $allowEditing, $fileContents_R);
$$usingCM_R = 'false';
$$textHolderName_R = 'scrollTextRightOfContents';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$$customCSS_R = $cssForNonCm;
$$textTableCSS_R = $cssForNonCmTables;
}
elsif ($filePath =~ m!\.pod$!i)
{
GetPrettyPod($formH, $peeraddress, $clientIsRemote, $allowEditing, $fileContents_R);
$$usingCM_R = 'false';
$$textHolderName_R = 'scrollTextRightOfContents';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$$customCSS_R = $cssForNonCm . "\n" . $cssForPod;
$$textTableCSS_R = $cssForNonCmTables;
}
elsif ($filePath =~ m!\.(txt|log|bat)$!i)
{
# Glossary files get a special table of contents, and not much else.
if ($filePath =~ m![\\/]$GLOSSARYFILENAME$!i || $filePath =~ m![\\/]glossary.txt$!i)
{
GetPrettyGlossaryFile($formH, $peeraddress, $clientIsRemote, $allowEditing, $fileContents_R, undef);
}
else
{
# By default this runs the text through a Gloss processor.
# So all your .txt files are belong to Gloss.
GetPrettyTextContents($formH, $peeraddress, $clientIsRemote, $allowEditing, $fileContents_R, undef);
}
$$usingCM_R = 'false';
$$textHolderName_R = 'scrollTextRightOfContents';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
# Code block syntax highlighting with lolight, only for .txt files:
if ($filePath =~ m!\.txt|$!)
{
$cssForNonCm .= "\n" . '<link rel="stylesheet" href="lolight_custom.css" />';
}
$$customCSS_R = $cssForNonCm;
$$textTableCSS_R = $cssForNonCmTables;
}
# 2.1 custom, no TOC: md (Markdown)
elsif ($filePath =~ m!\.md$!i)
{
GetPrettyMD($formH, $peeraddress, $fileContents_R);
$$usingCM_R = 'false';
$$textHolderName_R = 'scrollText';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$$customCSS_R = $cssForMD;
$$textTableCSS_R = $cssForNonCmTables;
}
else
{
my $toc = '';
GetCMToc($filePath, \$toc);
if ($toc ne '')
{
$$textHolderName_R = 'scrollTextRightOfContents';
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$$customCSS_R = $cssForCM;
$$fileContents_R = "<div id='scrollContentsList'>$toc</div>" . "<div id='scrollTextRightOfContents'></div>";
}
else
{
$$meta_R = '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
$$customCSS_R = $cssForCM;
$$fileContents_R = "<div id='scrollText'></div>";
}
}
}
# Content for Edit button at top of View. Images don't have an Edit button.
# Word and pdf have an Edit button only if client is on the IntraMine server (!$clientIsRemote).
sub EditButton {
my ($host, $filePath, $clientIsRemote, $allowEditing) = @_;
my $result = '';
# No Edit button if it's an image.
my $canEdit = ($filePath !~ m!\.(png|gif|jpe?g|ico|webp)$!i);
if (!$allowEditing)
{
$canEdit = 0;
}
# No remote Edit for docx|pdf
if ($canEdit)
{
if ($clientIsRemote && $filePath =~ m!\.(docx|pdf)$!i)
{
$canEdit = 0;
}
}
# Edit button, text files will open with IntraMine's Editor or your preferred app,
# the final decision being made in viewerlinks.js#editOpen().
if (!$canEdit)
{
; # leave action empty
}
else
{
$result = <<'FINIS';
<a href='_FILEPATH_' onclick='editOpen(this.href); return false;'><input class="submit-button" type="submit" value="Edit" /></a>
FINIS
#<a href='_FILEPATH_' onclick='editWithPreferredApp(this.href); return false;'><img src='edit_55_22.png'></a>
# TEST ONLY encode_utf8 out
my $encFilePath = $filePath;
#my $encFilePath = encode_utf8($filePath);
$encFilePath =~ s!\\!/!g;
$encFilePath =~ s!^file\:///!!;
$encFilePath =~ s!%!%25!g;
$encFilePath =~ s!\+!\%2B!g;
# prob not needed $encFilePath = &HTML::Entities::encode($encFilePath);
$result =~ s!_FILEPATH_!$encFilePath!;
}
return($result);
}
# If we arrived at this View from Search results, get highlight information for inserting
# into the returned page: see _HIGHLIGHTITEMS_ in FullFileTemplate().
# For non-CodeMirror files, just poke the individual search words into an array.
# For CodeMirror, build a list of all the hits in the text of the file,
# array of "[line, charStart, charEnd]". Only the first 50 hits are done for CodeMirror.
# For non-CodeMirror files, the price of marking all occurrences is we must avoid
# marking one or two-letter words, otherwise things stall out in large files.
sub InitialHighlightItems {
my ($formH, $usingCM, $searchItems) = @_;
my $highlightItems = '';
if ($searchItems ne '')
{
my $forExactPhrase = ($searchItems =~ m!^\"!);
# Fix up special characters such as ' __D_ '.
DecodeSpecialNonWordCharacters(\$searchItems);
$searchItems = lc($searchItems);
$searchItems =~ s!\"!!g;
my @items = split(/ +/, $searchItems);
if ($usingCM eq 'true')
{
if ($forExactPhrase)
{
@items = ();
push @items, $searchItems;
}
GetCodeMirrorSearchHitPositions($formH, \@items, \$highlightItems);
}
else
{
if ($forExactPhrase)
{
if (length($searchItems) > 2)
{
$highlightItems = "\"$searchItems\"";
}
}
else
{
my $numItems = @items;
my $numSoFar = 0;
for (my $i = 0; $i < $numItems; ++$i)
{
if (length($items[$i]) > 2)
{
if ($numSoFar == 0)
{
$highlightItems = "\"$items[$i]\"";
}
else
{
$highlightItems .= ",\"$items[$i]\"";
}
++$numSoFar;
}
}
}
}
}
my $toggleHitsButton = '';
if ($highlightItems ne '')
{
$toggleHitsButton = '<input onclick="toggleInitialSearchHits();" id="sihits" class="submit-button" type="submit" value="Hide Initial Hits" />';
}
return($highlightItems, $toggleHitsButton);
}
sub DecodeSpecialNonWordCharacters {
my ($txtR) = @_;
$$txtR =~ s! *__D_ *!\.!g;
$$txtR =~ s!__DS_([A-Za-z])!\$$1!g;
$$txtR =~ s!__L_([A-Za-z])!\~$1!g;
$$txtR =~ s!__PC_([A-Za-z])!\%$1!g;
$$txtR =~ s!__AT_([A-Za-z])!\@$1!g;
}
sub PositionToggle {
my $result = '<input onclick="toggle();" id="togglehits" class="submit-button" type="submit" value="Toggle" />';
return($result);
}
sub InlineHoverButton {
my ($filePath) = @_;
my $result = '';
if ($filePath !~ m!\.txt$!i)
{
return($result);
}
$result = '<input onclick="toggleImagesButton();" id="inlineImages" class="submit-button" type="submit" value="Inline Images" />';
return($result);
}
# CodeMirror JavaScript and non-CodeMirror JS are rather different, especially in the way that
# such things as links and highlights are handled. For non-CodeMirror, links and highlights
# are put right in the HTML, whereas CodeMirror links and highlights are handled with
# overlay markers (for an overview of that, see https://codemirror.net/doc/manual.html#markText).
sub CodeMirrorJS {
my $jsFiles = <<'FINIS';
<script src="lib/codemirror.js" ></script>
<script src="addon/mode/loadmode.js"></script>
<script src="mode/meta.js"></script>
<script src="addon/dialog/dialog.js"></script>
<script src="addon/search/search.js"></script>
<script src="addon/scroll/annotatescrollbar.js"></script>
<script src="addon/search/matchesonscrollbar.js"></script>
<script src="addon/search/searchcursor.js"></script>
<script src="addon/search/match-highlighter.js"></script>
<script src="addon/search/jump-to-line.js"></script>
<script src="addon/edit/matchbrackets.js"></script>
<script src="intramine_config.js"></script>
<script src="spinner.js"></script>
<script src="websockets.js"></script>
<script src="topnav.js"></script>
<script src="todoFlash.js"></script>
<script src="chatFlash.js"></script>
<script src="isW.js" ></script>
<script src="cmViewerStart.js" ></script>
<script src="viewerLinks.js" ></script>
<script src="cmAutoLinks.js" ></script>
<script src="cmTocAnchors.js" ></script>
<script src="cmViewerMobile.js" ></script>
<script src="showHideTOC.js" ></script>
<script src="cmShowSearchItems.js" ></script>
<script src="cmToggle.js" ></script>
<script src="cmScrollTOC.js" ></script>
<script src="dragTOC.js" ></script>
<script src="viewer_auto_refresh.js" ></script>
<script src="cmHandlers.js" ></script>
FINIS
return($jsFiles);
}
# JavaScript for non-CodeMirror "custom" views (text, Perl and a few others).
sub NonCodeMirrorJS {
my $jsFiles = <<'FINIS';
<script src="intramine_config.js"></script>
<script src="spinner.js"></script>
<script src="websockets.js"></script>
<script src="topnav.js"></script>
<script src="todoFlash.js"></script>
<script src="chatFlash.js"></script>
<script src="isW.js" ></script>
<script src="mark.min.js" ></script>
<script src="wordAtInsertionPt.js" ></script>
<script src="LightRange.min.js" ></script>
<script src="commonEnglishWords.js" ></script>
<script src="viewerStart.js" ></script>
<script src="autoLinks.js" ></script>
<script src="showHideTOC.js" ></script>
<script src="viewerLinks.js" ></script>
<script src="indicator.js" ></script>
<script src="toggle.js" ></script>
<script src="scrollTOC.js" ></script>
<script src="viewer_auto_refresh.js" ></script>
<script src="dragTOC.js" ></script>
<script src="viewer_hover_inline_images.js" ></script>
<script>
hideSpinner();
</script>
FINIS
return($jsFiles);
}
# "req=loadfile" handling. For CodeMirror views, the text is loaded by JavaScript after the
# page starts up, see cmViewerStart.js#loadFileIntoCodeMirror().
sub LoadTheFile {
my ($obj, $formH, $peeraddress) = @_;
my $result = '';
my $filepath = defined($formH->{'file'})? $formH->{'file'}: '';
if ($filepath ne '')
{
$result = uri_escape_utf8(ReadTextFileDecodedWide($filepath));
if ($result eq '' && FileOrDirExistsWide($filepath) == 1)
{
$result = '___THIS_IS_ACTUALLY_AN_EMPTY_FILE___';
}
#####$result = uri_escape_utf8(ReadTextFileWide($filepath));
}
return($result);
}
# Open a directory link using Windows File Explorer.
sub OpenDirectory {
my ($obj, $formH, $peeraddress) = @_;
my $result = 'OK';
my $dirPath = defined($formH->{'dir'})? $formH->{'dir'}: '';
if ($dirPath eq '')
{
$result = 'ERROR, no directory supplied!';
}
else
{
$dirPath =~ s!^file\:///!!g;
# DAAAMM this is ugly.
# https://www.perlmonks.org/?node_id=1162804
$dirPath = Encode::encode("CP1252", $dirPath);
system('start', '', $dirPath);
}
return($result);
}
# "req=loadfile" handling. For CodeMirror views, the text is loaded by JavaScript after the
# page starts up, see cmViewerStart.js#loadFileIntoCodeMirror().
sub olderLoadTheFile {
my ($obj, $formH, $peeraddress) = @_;
my $result = '';
my $filepath = defined($formH->{'file'})? $formH->{'file'}: '';
if ($filepath ne '')
{
my $ctrlSPath = $filepath;
$ctrlSPath = encode_utf8($ctrlSPath);
$ctrlSPath =~ s!%!%25!g;
$ctrlSPath =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
$result = GetHtmlEncodedTextFile($filepath);
}
return($result);
}
# Straight HTML. Note resulting page has no TopNav.
sub GetHTML {
my ($formH, $peeraddress, $contentsR) = @_;
my $filePath = $formH->{'FULLPATH'};
$$contentsR = "";
my $sourceFileH = GetExistingReadFileHandleWide($filePath);
if (!defined($sourceFileH))
{
my $exists = FileOrDirExistsWide($filePath);
if ($exists == 1)
#if (-f $filePath)
{
$$contentsR .= "Error, could not open $filePath.";
}
else
{
$$contentsR .= "Error, $filePath does not exist.";
}
return;
}
my $inStr = '';
my $line = '';
my @lines;
while ($line = <$sourceFileH>)
{
chomp $line;
push @lines, $line;
}
close $sourceFileH;
$$contentsR .= join("\n", @lines);
}
sub GetImageLink {
my ($formH, $peeraddress, $port, $contentsR) = @_;
my $fileLocation = $formH->{'FULLPATH'};
my $serverAddr = ServerAddress();
$fileLocation =~ s!%!%25!g;
$fileLocation = &HTML::Entities::encode($fileLocation);
my $imagePath = "http://$serverAddr:$port/$fileLocation";
$$contentsR = "<img src='$imagePath'>";
}
# PDF: requires having swarmserver.pm#Respond() add a couple of headers to response.
sub GetPDF {
my ($formH, $peeraddress, $contentsR) = @_;
my $fileLocation = $formH->{'FULLPATH'};
$$contentsR = GetBinFile($fileLocation);