-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
1156 lines (979 loc) · 39.5 KB
/
Program.cs
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
using Terminal.Gui;
using SmolNetSharp.Protocols;
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Extensions.CommandLineUtils;
namespace Romulus
{
class Program
{
private static MenuItem _homeMenu;
private static MenuBarItem _bookmarksMenu;
private static MenuBarItem[] _bookmarkItems;
private static MenuBarItem[] _structureMenuItems;
private static MenuBarItem _structureMenu;
private static Uri _homeUri;
private static Toplevel _top;
private static string _aboutFolder;
private static Uri _initialUri;
private static Stack<CachedPage> _history;
private static ListView _lineView;
private static Uri _currentUri;
private static Window _win;
private static MenuBar _menu;
private static int _charWrap;
//private static bool insecure;
static void Main(string[] args)
{
CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false);
//CommandOption cert = commandLineApplication.Option(
// "-c | --cert <path>", "path to pfx certificate",
// CommandOptionType.SingleValue);
//CommandOption insecureFlag = commandLineApplication.Option(
// "-i | --insecure", "connect without checking server cert",
// CommandOptionType.NoValue);
//commandLineApplication.HelpOption("-? | -h | --help");
_charWrap = 75; //default - can provide UI for ths
CommandOption charWrap = commandLineApplication.Option(
"-w | --charWrap", "wrap content at this column",
CommandOptionType.SingleValue);
commandLineApplication.ExtendedHelpText = "Romulus <url>";
string startUrl = "";
commandLineApplication.OnExecute(() =>
{
_homeUri = new Uri("about:home");
_initialUri = _homeUri;
_charWrap = charWrap.HasValue() ? int.Parse(charWrap.Value()) : 75;
if (commandLineApplication.RemainingArguments.Count > 0)
{
startUrl = commandLineApplication.RemainingArguments[0].ToString(); //use the first one
if (TextIsUri(startUrl))
{
var candidateUri = new Uri(startUrl);
if ((candidateUri.Scheme == "gemini") || (candidateUri.Scheme == "about"))
{
//these are the only valid starup URls
_initialUri = candidateUri;
}
}
}
//insecure = (bool)insecureFlag.HasValue();
Application.Init();
_top = Application.Top;
_history = new Stack<CachedPage>();
_aboutFolder = AppDomain.CurrentDomain.BaseDirectory;
_currentUri = null;
_bookmarkItems = new MenuBarItem[] { };
_bookmarksMenu = new MenuBarItem(_bookmarkItems);
_bookmarksMenu.Title = "Book_marks";
_structureMenuItems = new MenuBarItem[] { };
_structureMenu = new MenuBarItem(_structureMenuItems);
_structureMenu.Title = "_Structure";
_homeMenu = new MenuItem("_Home", "", () => { LoadHandledLink(_homeUri); });
_homeMenu.Shortcut = Key.AltMask & Key.H;
// Creates the top-level window to show
_win = new Window("Romulus Gemini Application")
{
X = 0,
Y = 1, // Leave one row for the toplevel menu
ColorScheme = Colors.Menu, //to blend with menu
// By using Dim.Fill(), it will automatically resize without manual intervention
Width = Dim.Fill(),
Height = Dim.Fill()
};
_top.Add(_win);
_lineView = new ListView()
{
X = 2,
Y = 1,
Height = Dim.Fill() - 1,
Width = Dim.Fill() - 1,
ColorScheme = Colors.Menu, //to blend with window and menu background
};
_lineView.OpenSelectedItem += (ListViewItemEventArgs e) =>
{
HandleActivate(e.Value, _currentUri);
};
_lineView.KeyPress += (View.KeyEventEventArgs e) =>
{
if (e.KeyEvent.Key == Key.Tab)
{
JumpLink(1);
e.Handled = true;
}
else if (e.KeyEvent.Key == Key.BackTab)
{
JumpLink(-1);
e.Handled = true;
}
};
// Creates a menubar, the item "New" has a help menu.
_menu = new MenuBar(new MenuBarItem[] {
new MenuBarItem ("_File", new MenuItem [] {
new MenuItem("_Open URL", "", () => {OpenUserChosenUri(); }),
new MenuItem("_Reload", "", () => {Reload(); }),
_homeMenu,
new MenuItem ("_Quit", "", () => { if (Quit ()) _top.Running = false; })
}),
_bookmarksMenu,
_structureMenu,
new MenuBarItem("_Back", "", () => {GoBack(); }),
});
LoadBookmarks();
_top.Add(_menu);
// Add some controls,
_win.Add(
// The ones with a computed layout system,
_lineView
);
//For some unknown reason _top.Ready is not firing in linux until the user moves a mouse or touches the keyboard.
//so we initialise on Loaded, which seems to work
_top.Loaded += () =>
{
LoadHandledLink(_initialUri);
};
Application.Run();
return 0;
});
commandLineApplication.Execute(args);
}
static bool Quit()
{
var n = MessageBox.Query(50, 7, "Quit Romulus", "Are you sure you want to quit Romulus?", "Yes", "No");
return n == 0;
}
static void JumpLink(int direction)
{
var gemLines = (List<GeminiLine>)_lineView.Source.ToList();
var selected = _lineView.SelectedItem;
int curIndex;
if (direction > 0)
{
if (selected == gemLines.Count - 1)
{
return;
} else
{
curIndex = selected + 1; //start from next item when scanning forwards
}
} else
{
if (selected == 0)
{
return;
} else
{
curIndex = selected - 1; //start from previous item when scanning backwards
}
}
while ((curIndex >= 0) && (curIndex < _lineView.Source.Count))
{
var gemLine = (GeminiLine)gemLines[curIndex];
if (gemLine.LineType == "=>")
{
EnsureVisibleLine(curIndex);
return; //we are done
}
if (direction > 0)
{
curIndex++; //forwards
} else
{
curIndex--; //backwards
}
}
}
//would be nice if this was an intrinsic method for the listview, but it is missing
static void EnsureVisibleLine(int lineIndex)
{
int topH, winH, listH, menuH;
if (
((View)_top).GetCurrentHeight(out topH)
)
{
((View)_menu).GetCurrentHeight(out menuH);
((View)_win).GetCurrentHeight(out winH);
((View)_lineView).GetCurrentHeight(out listH);
//calculate the inner height of the listview based on how we understand the
//overall layout, so some assumptions here about window design etc
int winInnerH = (topH - menuH) - 2; //2 for window border
int listInnerH = winInnerH + listH; //accomodate line view margin
if (
(lineIndex >= _lineView.TopItem) &&
(lineIndex <= _lineView.TopItem + listInnerH))
{
//its in view so just highlight it
} else
{
//scroll to show the item
_lineView.TopItem = lineIndex;
}
_lineView.SelectedItem = lineIndex;
//seems to be a bug maybe in terminal.gui that the window is not repainted after the selection
//so we force a repaint and focus
_lineView.SetFocus();
_win.Redraw(_win.Bounds);
}
}
static void BuildStructureMenu(List<GeminiLine> displayLines)
{
var bms = new List<MenuItem>();
var lineNum = 0;
var accelerators = new List<string>();
foreach (var line in displayLines)
{
var n = lineNum;
if ((line.LineType == "#") || (line.LineType == "##") || (line.LineType == "###"))
{
var m = new MenuItem();
var menuPrefix = "";
var accel = line.Line.Substring(0, 1);
if (!accelerators.Contains(accel))
{
menuPrefix = "_";
accelerators.Add(accel);
}
bms.Add(new MenuItem()
{
Title = line.LineType.Replace("#", " ").Substring(1) +
menuPrefix + line.Line,
Action = () =>
{
EnsureVisibleLine(n);
},
});
}
lineNum++;
}
_structureMenu.Children = bms.ToArray();
}
static void GoBack()
{
if (_history.Count > 1)
{
//take off the item on the top of the history (current page)
//then go to the one behind it from the cache
_history.Pop();
var cached = _history.Peek();
RenderGemini(cached.uri.AbsoluteUri, cached.content, _lineView);
_lineView.SelectedItem = cached.selected;
_lineView.ScrollDown(cached.top);
SetAsCurrent(cached.uri);
}
}
static void SetAsCurrent(Uri uri)
{
_currentUri = uri;
_win.Title = "Romulus: " + _currentUri.Authority + _currentUri.PathAndQuery;
}
static void Reload()
{
if (_currentUri != null)
{
_history.Pop(); //remove current it will be the same as reloaded Uri, so we only get one history entry
LoadGeminiLink(_currentUri);
}
}
private static void OpenUserChosenUri()
{
var userResponse = Dialogs.SingleLineInputBox("Gemini URL", "Enter the Gemini URL to load:", "");
if ((userResponse.ButtonPressed == TextDialogResponse.Buttons.Ok) &&
(userResponse.Text != ""))
{
var targetUrl = userResponse.Text;
if (!TextIsUri(targetUrl))
{
if(!targetUrl.StartsWith("gemini://")) //user may omit scheme and just give domain etc.
{
targetUrl = "gemini://" + targetUrl;
}
}
var uri = new Uri(targetUrl);
LoadHandledLink(uri);
}
}
static bool TextIsUri(string text)
{
Uri outUri;
return Uri.TryCreate(text, UriKind.Absolute, out outUri);
}
static string ReadAboutSchemeFile(Uri uri)
{
var file = Path.Combine(_aboutFolder, uri.AbsolutePath + ".gmi"); //about:foo is loaded from foo.gmi
if (File.Exists(file))
{
return File.ReadAllText(file);
} else
{
return "No such resource: " + uri.AbsoluteUri;
}
}
static void WriteAboutSchemeFile(Uri uri, string content)
{
var file = Path.Combine(_aboutFolder, uri.AbsolutePath + ".gmi"); //about:foo is loaded from foo.gmi
File.WriteAllText(file, content);
}
static void LoadAboutLink(Uri uri)
{
//special treatment for about: scheme
if (uri.Scheme == "about")
{
var result = ReadAboutSchemeFile(uri);
RenderGemini(uri.AbsoluteUri, result, _lineView);
_history.Push(new CachedPage(uri, result, 0, 0));
SetAsCurrent(uri);
return;
}
}
static void LoadHandledLink(Uri uri)
{
if (uri.Scheme == "gemini")
{
LoadGeminiLink(uri);
}
else if (uri.Scheme == "about")
{
LoadAboutLink(uri);
}
else
{
//not valid as a page to display
Dialogs.MsgBoxOK("Loading link", "Not a valid link to display: " + uri.AbsoluteUri);
}
}
static void LoadGeminiLink(Uri uri)
{
string result;
bool retrieved = false;
GeminiResponse resp;
resp = new GeminiResponse();
try
{
resp = (GeminiResponse)Gemini.Fetch(uri);
retrieved = true;
}
catch (Exception e)
{
//the native gui.cs Messagebox does not resize to show enough content
//so we use our own that is better
Dialogs.MsgBoxOK("Gemini error", uri.AbsoluteUri + "\n\n" + e.Message);
}
if (retrieved)
{
if (resp.codeMajor == '2')
{
//examine the first component of the media type up to any semi colon
switch (resp.mime.Split(';')[0].Trim())
{
case "text/gemini":
case "text/plain":
case "text/html":
{
string body = Encoding.UTF8.GetString(resp.bytes.ToArray());
result = (body);
if (!resp.mime.StartsWith("text/gemini"))
{
//display as preformatted text
result = "```\n" + result + "\n```\n";
}
break;
}
default: // report the mime type only for now
result = ("Some " + resp.mime + " content was received, but cannot currently be displayed.");
break;
}
//render the content and add to history
SetAsCurrent(resp.uri); //remember the final URI, since it may have been redirected.
if (_history.Count > 0)
{
_history.Peek().top = _lineView.TopItem;
_history.Peek().selected = _lineView.SelectedItem; //remember the line offset of the current page
}
_history.Push(new CachedPage(resp.uri, result, 0, 0));
RenderGemini(resp.uri.AbsoluteUri, result, _lineView);
}
else if (resp.codeMajor == '1')
{
//input requested from server
var userResponse = Dialogs.SingleLineInputBox("Input request from: " + uri.Authority, resp.meta, "");
if ((userResponse.ButtonPressed == TextDialogResponse.Buttons.Ok) && (userResponse.Text != ""))
{
var ub = new UriBuilder(uri);
ub.Query = userResponse.Text;
LoadGeminiLink(ub.Uri);
}
}
else if ((resp.codeMajor == '5') && (resp.codeMinor == '1'))
{
//not found
Dialogs.MsgBoxOK("Not found", "The resource was not found on the server: \n\n" + resp.uri.AbsoluteUri);
} else
{
Dialogs.MsgBoxOK("Gemini server response", uri.AbsoluteUri + "\n\n" + "Status: " + resp.codeMajor + resp.codeMinor + ": " + resp.meta);
}
}
}
static void SubmitNimigem(Uri nimigemUri, byte[] payload, string mime)
{
var resp = (NimigemResponse)Nimigem.Fetch(nimigemUri, payload, mime);
if ((resp.codeMajor == '2') && (resp.codeMinor == '5'))
{
//success status 25 - fetch the Gemini target
LoadGeminiLink(new Uri(resp.meta));
}
else
{
//everything else is a problem for now
Dialogs.MsgBoxOK("Error", "Could not send content. Server Message was: \n" + resp.meta);
}
}
static void HandleNimigemActivate(Uri uri)
{
var preformattedLines = new List<GeminiLine>();
var exitedPreformatted = false;
var enteredPreformat = false;
var foundNimigemEdit = false;
var currentLine = _lineView.SelectedItem;
var activatedLine = (GeminiLine)_lineView.Source.ToList()[currentLine];
//check if it is hinted as a null payload link
if (activatedLine.Line.StartsWith('\u2205'.ToString())) {
//send null payload
try
{
SubmitNimigem(uri, Encoding.UTF8.GetBytes(""), "text/plain");
}
catch (Exception e)
{
Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: " + e.Message);
}
return;
}
//search back in the page for the linked text area
//gather the previous nimigem lines and let the user edit the text
while (currentLine >= 0)
{
var gemLine = (GeminiLine)_lineView.Source.ToList()[currentLine];
if (gemLine.LineType == "```+")
{
enteredPreformat = true;
foundNimigemEdit = true; //strictly speaking this will ignore all nimigem areas that are empty...
}
if (enteredPreformat & gemLine.LineType != "```+")
{
exitedPreformatted = true;
}
if (!exitedPreformatted && enteredPreformat && gemLine.LineType == "```+")
{
//we found a line in the first preceeding preformatted area
preformattedLines.Add(gemLine);
}
currentLine--;
}
var sb = new StringBuilder();
preformattedLines.Reverse();
for (int n = 0; n < preformattedLines.Count; n++)
{
var editLine = preformattedLines[n];
//nimigem spec requires any required preformatted markers inside
//editable preformatted areas to be escaped with zero width space
if (editLine.Line.StartsWith('\u200b'.ToString() + "```"))
{
sb.Append(editLine.Line.Substring(1)); //trim leading zero width space used to escape preformatted markers
}
else
{
sb.Append(editLine.Line);
}
//append newline to all except the last one
if (n < preformattedLines.Count - 1)
{
sb.Append("\n");
}
}
if (foundNimigemEdit)
{
var userEdit = Dialogs.MultilineInputBox("Nimigem edit", "Edit the text to be sent to: " + uri.AbsoluteUri, sb.ToString());
if (userEdit.ButtonPressed == TextDialogResponse.Buttons.Ok)
{
try
{
//send as plain text, utf8
SubmitNimigem(uri, Encoding.UTF8.GetBytes(userEdit.Text), "text/plain");
}
catch (Exception e)
{
Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: \n" + e.Message);
}
}
}
else
{
//No associated preceding Nimigem editable preformatted area was found.
//so send a file
//show a dialog to choose a file
var openDialog = new Terminal.Gui.OpenDialog("Nimigem upload", "Choose a file to send to the Nimigem server");
Application.Run(openDialog);
if (openDialog.FilePaths.Count > 0)
{
var selectedPath = openDialog.FilePaths[0];
var bytes = File.ReadAllBytes(selectedPath);
var extension = Path.GetExtension(selectedPath);
// since text/gemini is not widely known but might be more common for users of a gemini client
// we test for it, otherwise we use the MimeTypes library to infer it
var mediaType = (extension == ".gmi" || extension == ".gemini") ? "text/gemini" : MimeTypes.GetMimeType(selectedPath);
try
{
SubmitNimigem(uri, bytes, mediaType); //send to the server
}
catch (Exception e)
{
Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: \n" + e.Message);
}
}
}
}
static bool IsHandledScheme(string link) {
var result = false;
Uri outUri;
if (Uri.TryCreate(link, UriKind.Absolute, out outUri)) {
if (
outUri.Scheme == "gemini" ||
outUri.Scheme == "nimigem" ||
outUri.Scheme == "about" ||
outUri.Scheme == "http" ||
outUri.Scheme == "https"
) {
return true;
}
}
return result;
}
static void HandleActivate(Object item, Uri currentUri)
{
var line = (GeminiLine)item;
if (line.LineType == "=>")
{
var link = line.Link;
if (TextIsUri(link) && IsHandledScheme(link))
{
//is a full URL
var uri = new Uri(link);
if (uri.Scheme == "gemini")
{
LoadGeminiLink(uri);
}
else if (uri.Scheme == "about")
{
LoadAboutLink(uri);
}
else if (uri.Scheme == "http" || uri.Scheme == "https")
{
//launch in the system web browser
OpenBrowser(uri.AbsoluteUri);
}
else if (uri.Scheme == "nimigem")
{
HandleNimigemActivate(uri);
}
else
{
//nothing else handled at the moment
Dialogs.MsgBoxOK("Opening link: " + uri.Scheme, uri.Scheme.ToUpper() + " links are not currently handled.");
}
}
else
{
//is a relative path, build it relative to current
var assembledUri = new Uri(currentUri, link);
LoadGeminiLink(assembledUri);
}
}
}
static bool PrettifyWithExtraLine(string sourceline, string lineType, string lastLine, string lastLogicalType, bool preformat)
{
//if current or previous actual line is empty, dont add one
if (sourceline.Trim() == "") { return false; }
if (lastLine.Trim() == "") { return false; }
//dont add break when we go into preformat, and
//dont add break when we close the preformat
if (preformat && lineType != "```") { return false; }
if (!preformat && lineType == "```") { return false; }
//all other contiguous changes of type warrant a new line
if (lastLogicalType != lineType)
{
return true;
}
return false;
}
static string GetLineType(string sourceline)
{
var lineType = "p";
if (sourceline.StartsWith("###"))
{
lineType = "###";
}
else if (sourceline.StartsWith("##"))
{
lineType = "##";
}
else if (sourceline.StartsWith("#"))
{
lineType = "#";
}
else if (sourceline.StartsWith("=>"))
{
lineType = "=>";
}
else if (sourceline.StartsWith(">"))
{
lineType = ">";
}
else if (sourceline.StartsWith("* "))
{
lineType = "*";
}
else if (sourceline.StartsWith("```"))
{
lineType = "```";
}
if (sourceline == "")
{
lineType = "";
}
return lineType;
}
static void RenderGemini(string Url, string rawContent, ListView lineView)
{
var displayLines = new List<GeminiLine>();
int lineWidth;
var useContent = rawContent;
useContent = useContent.Replace("\r\n", "\n"); //normalise line endings
var sourcelines = useContent.Split('\n');
var intColwrap = _charWrap > 30 ? _charWrap : 30; //min wrap is 30, otherwise at user request
//we wrap content by fixed size at the moment
int paraWrap = intColwrap - 2; //default wrap for paragraphs, which are indented by 2
int otherWrap = intColwrap - 5; //for other line types we wrap smaller to accomodate deeper indent by extra 3
lineWidth = paraWrap; //default
bool preformat = false;
bool isNimigem = false;
string lastLine = "";
string lineType = "";
string lastLogicalType = "";
displayLines.Add(new GeminiLine("", "")); //add a blank line at the top for UI reasons - will be the default selected line
foreach (var sourceline in sourcelines)
{
lineType = GetLineType(sourceline);
if (lineType == "```") {
preformat = !preformat;
isNimigem = sourceline.StartsWith("```✏️"); //first character is pencil edit emoji
}
if (PrettifyWithExtraLine(sourceline, lineType, lastLine, lastLogicalType, preformat))
{
displayLines.Add(new GeminiLine("", ""));
}
if (lineType != "")
{
lastLogicalType = lineType;
}
lastLine = sourceline;
if (lineType != "```") //dont render toggle lines
{
if (preformat)
{
if (isNimigem)
{
lineType = "```+";
}
displayLines.Add(new GeminiLine(Utils.TabsToSpaces(sourceline), lineType, "", false, true));
}
else
{
lineWidth = otherWrap; //default assume indented, or a heading
var linkTarget = "";
var display = sourceline;
if (lineType == "=>")
{
var linkParts = Utils.ParseGeminiLink(sourceline);
linkTarget = linkParts[0];
display = linkParts[1];
}
else
{
if (lineType == "" || lineType == "p")
{
display = sourceline;
lineWidth = paraWrap; //not indented
}
else if (sourceline.Length > lineType.Length)
{
display = sourceline.Substring((lineType.Length)).Trim();
}
else
{
display = sourceline;
}
}
var wrapLines = Utils.WordWrap(display, lineWidth);
var count = 1;
foreach (var wrapLine in wrapLines)
{
displayLines.Add(new GeminiLine(Utils.TabsToSpaces(wrapLine), lineType, linkTarget, count > 1, false));
count++;
}
}
}
}
BuildStructureMenu(displayLines);
lineView.SetSource(displayLines);
}
// cross platform - launch the system web browser with the supplied url
// based on https://brockallen.com/2016/09/24/process-start-for-urls-on-net-core/
// hack because of this: https://github.com/dotnet/corefx/issues/10361
// with latter follow up to simplify using advice from
// https://github.com/dotnet/runtime/issues/17938
static void OpenBrowser(string url)
{
try
{
Process.Start(url);
}
catch
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = url,
UseShellExecute = true
};
Process.Start(psi);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
throw;
}
}
}
static void AddBookmark()
{
var bookmarkContent = ReadAboutSchemeFile(_homeUri);
var found = false;
var pageTitle = "";
//check if the bookmark is already in the list
foreach (var line in bookmarkContent.Split("\n"))
{
var lineData = Utils.ParseGeminiLink(line);
if (lineData[0] == _currentUri.AbsoluteUri)
{
found = true;
break;
}
}
if (found)
{
Dialogs.MsgBoxOK("Bookmark exists", "That URL is already in the bookmark list:\n\n" + _currentUri.AbsoluteUri);
}
else
{
bookmarkContent += "\n=> " + _currentUri.AbsoluteUri;
if (_structureMenu.Children.Length > 0)
{
pageTitle = _structureMenu.Children[0].Title.ToString();
if (pageTitle.StartsWith("_"))
{
pageTitle = pageTitle.Substring(1);
}
bookmarkContent += " " + pageTitle + " - " + (_currentUri.Scheme == "about" ? _currentUri.AbsoluteUri : _currentUri.Authority); //add this for context
}
WriteAboutSchemeFile(_homeUri, bookmarkContent);
if (_currentUri.AbsoluteUri == _homeUri.AbsoluteUri)
{
//user added link to home page, so reload it
var homeOffset = _lineView.TopItem;
var homeSelected = _lineView.SelectedItem;
Reload();
_lineView.TopItem = homeOffset;
_lineView.SelectedItem = homeSelected;
}
LoadBookmarks();
Dialogs.MsgBoxOK("Bookmark added", "Bookmark added to: " + _currentUri.AbsoluteUri);
}
}
static void LoadBookmarks()
{
var homeLines = ReadAboutSchemeFile(_homeUri).Split("\n");
var bms = new List<MenuItem>();
bms.Add(new MenuItem()
{
Title = "Add bookmark",
Action = () =>
{
AddBookmark();
}
});
bms.Add(new MenuItem()
{
Title = "─────────────────" //simplistic separator
});
foreach (var line in homeLines)
{
var linkinfo = Utils.ParseGeminiLink(line);
if (linkinfo[0] != null)
{
bms.Add(new MenuItem()
{
Title = "_" + linkinfo[1],
Action = () =>
{
LoadGeminiLink(new Uri(linkinfo[0]));
}
});
}
}
_bookmarksMenu.Children = bms.ToArray();
}