markdown.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #####################################################################
  2. # #
  3. # THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE #
  4. # LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet ) #
  5. # FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk ) #
  6. # WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
  7. # IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
  8. # OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE. #
  9. # #
  10. # ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS #
  11. # (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK. #
  12. # YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
  13. # THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER #
  14. # VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG #
  15. # WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ). #
  16. # #
  17. # THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE #
  18. # NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
  19. # THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT #
  20. # SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
  21. # THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT. #
  22. # #
  23. # THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL #
  24. # FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE #
  25. # THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD #
  26. # TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT. #
  27. # #
  28. #####################################################################
  29. import os
  30. from subprocess import *
  31. from gi.repository import Gtk
  32. from gi.repository import Gdk
  33. from gi.repository import Pango
  34. from flbry import ui
  35. ################################################################################
  36. # Markdown. Or .md file format is an easy way to give your simple text documents
  37. # a bit of flare. Stuff like links, images and quotes are supported. Also bold
  38. # an italic characters.
  39. def Open(md):
  40. # Spliting it for the read.
  41. md = "\n\n"+md
  42. md = md.split("\n")
  43. # First thing is I was to read the headings and convert it into a tree.
  44. tree = []
  45. indent = 1
  46. c = []
  47. skip = 0
  48. for n,line in enumerate(md):
  49. if skip > n:
  50. continue
  51. ty = "text"
  52. te = line
  53. # Here I want to simply get a type of each line. Later we going to parse
  54. # the links and other things. But first. Let's parse stuff based on
  55. # lines.
  56. if line.startswith("```"):
  57. # THREE ``` aka code block
  58. # This tag will block any other tags
  59. # untill it's untagged
  60. code = ""
  61. for l in md[n+1:]:
  62. if not l.startswith("```"):
  63. code = code + l + "\n"
  64. else:
  65. skip = n + code.count("\n") + 2
  66. break
  67. tree.append(["text_cm", code+"\n"])
  68. te = ""
  69. elif line.startswith("#"):
  70. # The titles of the chapter. The Headers are usually written similar
  71. # to how here in python you write comments. It's a # , space, and the
  72. # text.
  73. # The amount of hashes. ## or ### gives different sized text. Officialy
  74. # it should support up to 6 hashes. ######. But why not make it more
  75. # just in case.
  76. ty = line.count("#") # This might give bugs
  77. elif line.startswith(">"):
  78. # The > sign in the Markdown language is used for quatations.
  79. ty = "text_q"
  80. te = te[1:]
  81. tree.append([ty, te+"\n"])
  82. # Now the stage 0 is over and we parsed the basic things. Now is the hard
  83. # part to parse out all the images and stuff inside them. It's going to be
  84. # done per part. And we are going to use the same technique I used for the
  85. # conversion of the legacy projects. See : studio/story.py ( in VCStudio )
  86. # We are going to itterate over each letter. And decide what to do by that
  87. newtree = []
  88. for block in tree:
  89. if block[0] == "text_cm":
  90. newtree.append(block)
  91. continue
  92. part = ""
  93. skip = 0
  94. for n, l in enumerate(block[-1]):
  95. if skip > n:
  96. continue
  97. part = part + l
  98. # Here we are going to do something if a give condition is met.
  99. # Usually I gonna do something if [part] ends with a given markdown
  100. # thing. I don't have a manual of markdown on me. So please make it
  101. # more supported. I guess. I might forget things I rarely use.
  102. # Links are made with [stuff you click on](https://example.com)
  103. # but similar to it. Images are done ![Tooltip](Image.png)
  104. # and even weirder you can put one into the other. Like
  105. # [![Tooltip](Image.png)](https://example.com)
  106. # Which going to give you a clickable image.
  107. # For this version what we are going to do is next.
  108. # If we got [![ then it's a clickable image
  109. # If we got ![ then it's just image
  110. # and if we got [ then it's a link.
  111. if part.endswith("[!["):
  112. # IMAGE LINK
  113. newtree.append([block[0], part[:-3]])
  114. tooltip = ""
  115. imageurl = ""
  116. url = ""
  117. t = False
  118. iu = False
  119. skip = n
  120. for le in block[-1][n:]: # For letters in the rest of text
  121. skip = skip + 1
  122. if le == "]":
  123. t = True
  124. elif le == ")" and t and not iu:
  125. iu = True
  126. elif le == ")" and t and iu:
  127. break
  128. elif not t:
  129. tooltip = tooltip +le
  130. elif t and not iu:
  131. imageurl = imageurl + le
  132. else:
  133. url = url+le
  134. tooltip = tooltip[tooltip.find("[")+1:]
  135. imageurl = imageurl[imageurl.find("(")+1:]
  136. url = url[url.find("(")+1:]
  137. apnd = ["image_link", imageurl, url]
  138. newtree.append(apnd)
  139. part = ""
  140. elif part.endswith("!["):
  141. # IMAGE
  142. newtree.append([block[0], part[:-2]])
  143. tooltip = ""
  144. url = ""
  145. t = False
  146. skip = n
  147. for le in block[-1][n:]: # For letters in the rest of text
  148. skip = skip + 1
  149. if le == "]":
  150. t = True
  151. elif le == ")" and t:
  152. break
  153. elif not t:
  154. tooltip = tooltip +le
  155. else:
  156. url = url+le
  157. tooltip = tooltip[tooltip.find("[")+1:]
  158. url = url[url.find("(")+1:]
  159. apnd = ["image", "[IMAGE]", url]
  160. newtree.append(apnd)
  161. part = ""
  162. elif part.endswith("[") and not block[-1][n:].startswith('[!['):
  163. # LINK
  164. newtree.append([block[0], part[:-1]])
  165. tooltip = ""
  166. url = ""
  167. t = False
  168. skip = n
  169. for le in block[-1][n:]: # For letters in the rest of text
  170. skip = skip + 1
  171. if le == "]":
  172. t = True
  173. elif le == ")" and t:
  174. break
  175. elif not t:
  176. tooltip = tooltip +le
  177. else:
  178. url = url+le
  179. tooltip = tooltip[tooltip.find("[")+1:]
  180. url = url[url.find("(")+1:]
  181. apnd = ["link", tooltip, url]
  182. newtree.append(apnd)
  183. part = ""
  184. # Now I want to deal with `, *, ** and ***. If you want to help me you
  185. # can implement other types. Such as _, __, ___ and so on. Markdown is
  186. # a very rich language. I'm going to use the cut down version I see other
  187. # people use.
  188. # BTW this is the time. Feb 28. When I switched from Gedit to GNU Emacs.
  189. # Interesting feeling using this programm. I kind a love it even tho
  190. # so many stuff in not intuitive. Like saving is not Ctrl - S but
  191. # Ctrl - X -> Ctrl - S.
  192. # Things like Alt-; to comment multiple lines at ones is HUGE. Also it
  193. # was built by programmers for programmers. So it's a very good tool.
  194. elif part.endswith("**") and not block[-1][n+2:].startswith('*'):
  195. # DOUBLE **
  196. newtree.append([block[0], part[:-2]])
  197. if block[0] == "text":
  198. block[0] = "text_b"
  199. else:
  200. block[0] = "text"
  201. part = ""
  202. elif part.endswith("*") and not block[-1][n+1:].startswith('*'):
  203. # SINGLE *
  204. newtree.append([block[0], part[:-1]])
  205. if block[0] == "text":
  206. block[0] = "text_i"
  207. else:
  208. block[0] = "text"
  209. part = ""
  210. elif part.endswith("`"):
  211. # SINGLE `
  212. newtree.append([block[0], part[:-1]])
  213. if block[0] == "text":
  214. block[0] = "text_c"
  215. else:
  216. block[0] = "text"
  217. part = ""
  218. newtree.append([block[0], part])
  219. #newtree.append(["text", "\n"*20+" [END OF DOCUMENT] "])
  220. tree = newtree
  221. return(tree)
  222. def search_convert(s):
  223. # This function convers a chapter name into a link
  224. # such links are use in notabug.org to link to chapters
  225. # for example example.com/file.md#chapter-name
  226. # With this url it will load the example.com/file.md and
  227. # then skip to the "Chapter Name" chapter.
  228. # This function transforms "Chapter Name" into "chapter-name"
  229. l = " ./\|[]{}()?!@#$%^&*`~:;'\"=,<>"
  230. s = s.lower().replace(" ","-")
  231. r = ""
  232. for i in s:
  233. if i not in l:
  234. r = r + i
  235. return r
  236. def convert(win, text_view):
  237. text_buffer = text_view.get_buffer()
  238. st = text_buffer.get_start_iter()
  239. en = text_buffer.get_end_iter()
  240. text = text_buffer.get_text(st, en, True)
  241. text_buffer.set_text("")
  242. text_buffer.create_tag("text", justification=Gtk.Justification.FILL, left_margin=64, right_margin=64)
  243. text_buffer.create_tag("text_c", background="#eeeeee", foreground="#000000", font="Monospace", left_margin=64, right_margin=64)
  244. text_buffer.create_tag("text_b", font="Bold", justification=Gtk.Justification.FILL, left_margin=64, right_margin=64)
  245. text_buffer.create_tag("text_i", font="Italic", justification=Gtk.Justification.FILL, left_margin=64, right_margin=64)
  246. text_buffer.create_tag("text_q", justification=Gtk.Justification.FILL, left_margin=200, right_margin=200)
  247. text_buffer.create_tag("header", size_points=30, justification=Gtk.Justification.CENTER, left_margin=64, right_margin=64)
  248. text_view.set_justification(Gtk.Justification.CENTER)
  249. md = Open(text)
  250. markup = ""
  251. for i in md:
  252. en = text_buffer.get_end_iter()
  253. if type(i[0]) == str and i[0].startswith("text") and not i[0] == "text_cm":
  254. try:
  255. text_buffer.insert_with_tags_by_name(en, i[-1], i[0])
  256. except:
  257. text_buffer.insert(en, i[-1])
  258. elif i[0] == "text_cm":
  259. codeview = Gtk.TextView()
  260. #codeview.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(0.2,0.2,0.2, 1))
  261. #codeview.override_color(Gtk.StateType.NORMAL, Gdk.RGBA(0.9,0.9,0.9, 1))
  262. codeview.override_font(Pango.FontDescription("Monospace"))
  263. codescrl = Gtk.ScrolledWindow()
  264. codescrl.set_size_request(900, 500)
  265. codeview.set_editable(True)
  266. codescrl.add(codeview)
  267. codebuffer = codeview.get_buffer()
  268. codebuffer.set_text(i[-1])
  269. anchor = Gtk.TextChildAnchor()
  270. text_buffer.insert_child_anchor(en, anchor)
  271. text_view.add_child_at_anchor(codescrl , anchor)
  272. elif type(i[0]) == int:
  273. text_buffer.insert_with_tags_by_name(en, i[-1].replace("#", ""), "header")
  274. elif i[0] == "image_link":
  275. image = ui.load(win, ui.net_image_calculation, ui.net_image_render, i[1], 800, "", True)
  276. def link_launch(w, link):
  277. os.system("xdg-open "+link)
  278. def link_resolve(w, link):
  279. win.url.set_text(link)
  280. win.url.activate()
  281. optionsthing = Gtk.Popover()
  282. optbox = Gtk.VBox()
  283. optionsthing.add(optbox)
  284. opt_launch = Gtk.Button("Launch")
  285. optbox.pack_start(opt_launch, False, False, False)
  286. opt_resolve = Gtk.Button("Resolve")
  287. optbox.pack_start(opt_resolve, False, False, False)
  288. opt_launch.connect("clicked", link_launch, i[-1])
  289. opt_resolve.connect("clicked", link_resolve, i[-1])
  290. optbox.show_all()
  291. link = Gtk.MenuButton(popover=optionsthing)
  292. link.add(image)
  293. anchor = Gtk.TextChildAnchor()
  294. text_buffer.insert_child_anchor(en, anchor)
  295. text_view.add_child_at_anchor(link, anchor)
  296. elif i[0] == "image":
  297. image = ui.load(win, ui.net_image_calculation, ui.net_image_render, i[-1], 800, "", True)
  298. anchor = Gtk.TextChildAnchor()
  299. text_buffer.insert_child_anchor(en, anchor)
  300. text_view.add_child_at_anchor(image , anchor)
  301. elif i[0] == "link":
  302. # link = Gtk.LinkButton.new_with_label(
  303. # uri=i[-1],
  304. # label=i[1])
  305. def link_launch(w, link):
  306. os.system("xdg-open "+link)
  307. def link_resolve(w, link):
  308. win.url.set_text(link)
  309. win.url.activate()
  310. optionsthing = Gtk.Popover()
  311. optbox = Gtk.VBox()
  312. optionsthing.add(optbox)
  313. opt_launch = Gtk.Button("Launch")
  314. optbox.pack_start(opt_launch, False, False, False)
  315. opt_resolve = Gtk.Button("Resolve")
  316. optbox.pack_start(opt_resolve, False, False, False)
  317. opt_launch.connect("clicked", link_launch, i[-1])
  318. opt_resolve.connect("clicked", link_resolve, i[-1])
  319. optbox.show_all()
  320. link = Gtk.MenuButton(label=i[1], popover=optionsthing)
  321. link.set_tooltip_text(i[-1])
  322. anchor = Gtk.TextChildAnchor()
  323. text_buffer.insert_child_anchor(en, anchor)
  324. text_view.add_child_at_anchor(link, anchor)