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
 
 
 
 
 
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
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2021 Yorik van Havre <yorik@uncreated.net>              *
# *                                                                         *
# *   This program is free software; you can redistribute it and/or modify  *
# *   it under the terms of the GNU Lesser General Public License (LGPL)    *
# *   as published by the Free Software Foundation; either version 2 of     *
# *   the License, or (at your option) any later version.                   *
# *   for detail see the LICENCE text file.                                 *
# *                                                                         *
# *   This program is distributed in the hope that it will be useful,       *
# *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
# *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
# *   GNU Library General Public License for more details.                  *
# *                                                                         *
# *   You should have received a copy of the GNU Library General Public     *
# *   License along with this program; if not, write to the Free Software   *
# *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
# *   USA                                                                   *
# *                                                                         *
# ***************************************************************************

"""
Provide tools to access the FreeCAD documentation.

The main usage is using the "show" function. It can retrieve an URL,
a local file (markdown or html), or find a page automatically from
the settings set under Preferences->General->Help.

It doesn't matter what you give, the system will recognize if the contents are
HTML or Markdown and render it appropriately.

Basic usage:

    import Help
    Help.show("Draft Line")
    Help.show("Draft_Line") # works with spaces or underscores
    Help.show("https://wiki.freecad.org/Draft_Line")
    Help.show("https://gitlab.com/freecad/FreeCAD-documentation/-/raw/main/wiki/Draft_Line.md")
    Help.show("/home/myUser/.FreeCAD/Documentation/Draft_Line.md")
    Help.show("http://myserver.com/myfolder/Draft_Line.html")

Preferences keys (in "User parameter:BaseApp/Preferences/Mod/Help"):

    optionBrowser/optionTab/optionDialog (bool): Where to open the help dialog
    optionOnline/optionOffline (bool): where to fetch the documentation from
    URL (string): online location
    Location (string): offline location
    Suffix (string): a suffix to add to the URL, ex: /fr
    StyleSheet (string): optional CSS stylesheet to style the output

Defaults are to open the wiki in the desktop browser
"""

import os
import re
import urllib.request
import urllib.error
import FreeCAD


translate = FreeCAD.Qt.translate
QT_TRANSLATE_NOOP = FreeCAD.Qt.QT_TRANSLATE_NOOP

# texts and icons
WIKI_URL = "https://wiki.freecad.org"
MD_RAW_URL = "https://raw.githubusercontent.com/FreeCAD/FreeCAD-documentation/main/wiki"
MD_RENDERED_URL = "https://github.com/FreeCAD/FreeCAD-documentation/blob/main/wiki"
MD_TRANSLATIONS_FOLDER = "translations"
ERRORTXT = translate(
    "Help",
    "Contents for this page could not be retrieved. Please check settings under menu Edit → Preferences → General → Help",
)
LOCTXT = translate(
    "Help",
    "Help files location could not be determined. Please check settings under menu Edit → Preferences → General → Help",
)
LOGTXT = translate(
    "Help",
    "PySide QtWebEngineWidgets module is not available. Help rendering is done with the system browser",
)
CONVERTTXT = translate(
    "Help",
    "There is no Markdown renderer installed on your system, so this help page is rendered as is. Please install the Markdown or Pandoc Python modules to improve the rendering of this page.",
)
PREFS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Help")
ICON = ":/icons/help-browser.svg"


def show(page, view=None, conv=None):
    """
    show(page,view=None, conv=None):
    Opens a help viewer and shows the given help page.
    The given help page can be a URL pointing to a markdown or HTML file,
    a name page / command name, or a file path pointing to a markdown
    or HTML file. If view is given (an instance of openBrowserHTML.HelpPage or
    any other object with a 'setHtml()' method), the page will be
    rendered there, otherwise a new tab/widget will be created according to
    preferences settings. If conv is given (markdown, pandoc, github, builtin or
    none), the corresponding markdown conversion method is used. Otherwise, the
    module will use the best available.
    In non-GUI mode, this function simply outputs the markdown or HTML text.
    """

    page = underscore_page(page)
    location, _pagename = get_location(page)
    FreeCAD.Console.PrintLog("Help: opening " + location + "\n")
    if not location:
        FreeCAD.Console.PrintError(LOCTXT + "\n")
        return
    md = get_contents(location)
    html = convert(md, conv)
    baseurl = get_uri(location)
    if _pagename != "":
        pagename = _pagename
    else:
        pagename = os.path.basename(page.replace("_", " ").replace(".md", ""))
    title = translate("Help", "Help") + ": " + pagename
    if FreeCAD.GuiUp:
        if PREFS.GetBool("optionTab", False) and get_qtwebwidgets():
            # MDI tab
            show_tab(html, baseurl, title, view)
        elif PREFS.GetBool("optionDialog", False) and get_qtwebwidgets():
            # floating dock window
            show_dialog(html, baseurl, title, view)
        else:
            # desktop web browser - default
            show_browser(location)
    else:
        # console mode, we just print the output
        print(md)


def underscore_page(page):
    """change spaces by underscores in the given page name"""

    if "/" in page:
        page = page.split("/")
        page[-1] = page[-1].replace(" ", "_")
        page = "/".join(page)
    else:
        page.replace(" ", "_")
    return page


def get_uri(location):
    """returns a valid URI from a disk or network location"""

    baseurl = os.path.dirname(location) + "/"
    if baseurl.startswith("/"):  # unix path
        baseurl = "file://" + baseurl
    if baseurl[0].isupper() and (baseurl[1] == ":"):  # windows path
        baseurl = baseurl.replace("\\", "/")
        baseurl = "file:///" + baseurl
    return baseurl


def location_url(url_localized: str, url_english: str) -> tuple:
    """
    Returns localized documentation url and page name, if they exist,
    otherwise defaults to english version.
    Page name is gotten from:
      a) Name/* metadata tag on raw markdown files from github,
         Wiki translators should make sure to add it.
      b) <title> HTML tag
    """
    try:
        req = urllib.request.Request(url_localized)
        with urllib.request.urlopen(req) as response:
            html = response.read().decode("utf-8")
            if url_localized.startswith(MD_RAW_URL):
                pagename_match = re.search(r"Name/.*?:\s*(.+)", html)
            else:
                # Pages from FreeCAD Wiki fall here
                pagename_match = re.search(r"<title>(.*?) - .*?</title>", html)
            if pagename_match is not None:
                return (url_localized, pagename_match.group(1))
            else:
                return (url_localized, "")
    except urllib.error.HTTPError as e:
        return (url_english, "")


def get_location(page) -> tuple:
    """retrieves the location (online or offline) of a given page. Returns the location and the page name"""

    location = ""
    if page.startswith("http"):
        # NOTE: This gets activated when you open a link on the built-in browser, since
        # we don't know the URL, using location_url() fallback to the HTML <title> tag
        return location_url(page, page)
    if page.startswith("file://"):
        return (page[7:], "")
    # offline location
    if os.path.exists(page):
        return (page, "")
    page = page.replace(".md", "")
    page = page.replace(" ", "_")
    page = page.replace("wiki/", "")
    page = page.split("#")[0]
    suffix = PREFS.GetString("Suffix", "")
    pagename = ""
    if suffix:
        if not suffix.startswith("/"):
            suffix = "/" + suffix
    if PREFS.GetBool("optionWiki", True):  # default
        location, pagename = location_url(WIKI_URL + "/" + page + suffix, WIKI_URL + "/" + page)
    elif PREFS.GetBool("optionMarkdown", False):
        if PREFS.GetBool("optionBrowser", False):
            location = MD_RENDERED_URL
        else:
            location = MD_RAW_URL
        if suffix:
            location, pagename = location_url(
                location + "/" + MD_TRANSLATIONS_FOLDER + suffix + "/" + page + ".md",
                location + "/" + page + ".md",
            )
        else:
            location += "/" + page + ".md"
    elif PREFS.GetBool("optionGithub", False):
        location = MD_RENDERED_URL
        if suffix:
            location, pagename = location_url(
                location + "/" + MD_TRANSLATIONS_FOLDER + suffix + "/" + page + ".md",
                location + "/" + page + ".md",
            )
        else:
            location += "/" + page + ".md"
    elif PREFS.GetBool("optionCustom", False):
        location = PREFS.GetString("Location", "")
        if not location:
            location = os.path.join(
                FreeCAD.getUserAppDataDir(),
                "Mod",
                "offline-documentation",
                "FreeCAD-documentation-main",
                "wiki",
            )
        for ext in (".md", ".html", ".htm"):
            if os.path.exists(os.path.join(location, page + ext)):
                location = os.path.join(location, page + ext)
                break
    return (location, pagename)


def show_browser(url):
    """opens the desktop browser with the given URL"""

    from PySide import QtCore, QtGui

    try:
        ret = QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))
        if not ret:
            # some users reported problems with the above
            import webbrowser

            webbrowser.open_new(url)
    except:
        import webbrowser

        webbrowser.open_new(url)


def show_dialog(html, baseurl, title, view=None):
    """opens a dock dialog with the given html"""

    from PySide import QtCore

    if view:  # reusing existing view
        view.setHtml(html, baseUrl=QtCore.QUrl(baseurl))
        view.parent().parent().setWindowTitle(title)
    else:
        openBrowserHTML(html, baseurl, title, ICON, dialog=True)


def show_tab(html, baseurl, title, view=None):
    """opens a MDI tab with the given html"""

    from PySide import QtCore

    if view:  # reusing existing view
        view.setHtml(html, baseUrl=QtCore.QUrl(baseurl))
        view.parent().parent().setWindowTitle(title)
    else:
        openBrowserHTML(html, baseurl, title, ICON)


def get_qtwebwidgets():
    """verifies if qtwebengine is available"""

    try:
        from PySide import QtWebEngineWidgets
    except:
        FreeCAD.Console.PrintLog(LOGTXT + "\n")
        return False
    else:
        return True


def get_contents(location):
    """retrieves text contents of a given page"""

    import urllib

    if location.startswith("http"):
        import urllib.request

        try:
            r = urllib.request.urlopen(location)
        except:
            return ERRORTXT
        contents = r.read().decode("utf8")
        return contents
    else:
        if os.path.exists(location):
            with open(location, mode="r", encoding="utf8") as f:
                contents = f.read()
            return contents
    return ERRORTXT


def convert(content, force=None):
    """converts the given markdown code to html. Force can be None (automatic)
    or markdown, pandoc, github or raw/builtin"""

    import urllib

    def convert_markdown(m):
        try:
            import markdown
            from markdown.extensions import codehilite

            return markdown.markdown(m, extensions=["codehilite"])
        except:
            return None

    def convert_pandoc(m):
        try:
            import pypandoc

            return pypandoc.convert_text(m, "html", format="md")
        except:
            return None

    def convert_github(m):
        try:
            import json
            import urllib.request

            data = {"text": m, "mode": "markdown"}
            bdata = json.dumps(data).encode("utf-8")
            return (
                urllib.request.urlopen("https://api.github.com/markdown", data=bdata)
                .read()
                .decode("utf8")
            )
        except:
            return None

    def convert_raw(m):
        # simple and dirty regex-based markdown to html

        import re

        f = re.DOTALL | re.MULTILINE
        m = re.sub(r"^##### (.*?)\n", r"<h5>\1</h5>\n", m, flags=f)  # ##### titles
        m = re.sub(r"^#### (.*?)\n", r"<h4>\1</h4>\n", m, flags=f)  # #### titles
        m = re.sub(r"^### (.*?)\n", r"<h3>\1</h3>\n", m, flags=f)  # ### titles
        m = re.sub(r"^## (.*?)\n", r"<h2>\1</h2>\n", m, flags=f)  # ## titles
        m = re.sub(r"^# (.*?)\n", r"<h1>\1</h1>\n", m, flags=f)  # # titles
        m = re.sub(r"!\[(.*?)\]\((.*?)\)", r'<img alt="\1" src="\2">', m, flags=f)  # images
        m = re.sub(r"\[(.*?)\]\((.*?)\)", r'<a href="\2">\1</a>', m, flags=f)  # links
        m = re.sub(r"\*\*(.*?)\*\*", r"<b>\1</b>", m)  # bold
        m = re.sub(r"\*(.*?)\*", r"<i>\1</i>", m)  # italic
        m = re.sub(r"\n\n", r"<br/>", m, flags=f)  # double new lines
        m += "\n<br/><hr/><small>" + CONVERTTXT + "</small>"
        return m

    if "<html" in content:
        # this is html already
        return content

    if force == "markdown":
        html = convert_markdown(content)
    elif force == "pandoc":
        html = convert_pandoc(content)
    elif force == "github":
        html = convert_github(content)
    elif force in ["raw", "builtin"]:
        html = convert_raw(content)
    elif force == "none":
        return content
    else:
        # auto mode
        html = convert_pandoc(content)
        if not html:
            html = convert_markdown(content)
            if not html:
                html = convert_raw(content)
    if not "<html" in html:
        html = (
            '<html>\n<head>\n<meta charset="utf-8"/>\n</head>\n<body>\n\n'
            + html
            + "</body>\n</html>"
        )
    # insert css
    css = None
    cssfile = PREFS.GetString("StyleSheet", "")
    if not cssfile:
        cssfile = os.path.join(os.path.dirname(__file__), "default.css")
    if False:  # linked CSS file
        # below code doesn't work in FreeCAD apparently because it prohibits cross-URL stuff
        cssfile = urllib.parse.urljoin("file:", urllib.request.pathname2url(cssfile))
        css = '<link rel="stylesheet" type="text/css" href="' + cssfile + '"/>'
    else:
        if os.path.exists(cssfile):
            with open(cssfile) as cf:
                css = cf.read()
            if css:
                css = "<style>\n" + css + "\n</style>"
        else:
            print("Debug: Help: Unable to open css file:", cssfile)
    if css:
        html = html.replace("</head>", css + "\n</head>")
    return html


def add_preferences_page():
    """adds the Help preferences page to the UI"""

    import FreeCADGui

    page = os.path.join(os.path.dirname(__file__), "dlgPreferencesHelp.ui")
    FreeCADGui.addPreferencePage(page, QT_TRANSLATE_NOOP("QObject", "General"))


def add_language_path():
    """registers the Help translations to FreeCAD"""

    import FreeCADGui
    import Help_rc

    FreeCADGui.addLanguagePath(":/translations")


def openBrowserHTML(html, baseurl, title, icon, dialog=False):
    """creates a browser view and adds it as a FreeCAD MDI tab or dockable dialog"""

    import FreeCADGui
    from PySide import QtCore, QtGui, QtWidgets, QtWebEngineWidgets

    # turn an int into a qt dock area
    def getDockArea(area):
        if area == 1:
            return QtCore.Qt.LeftDockWidgetArea
        elif area == 4:
            return QtCore.Qt.TopDockWidgetArea
        elif area == 8:
            return QtCore.Qt.BottomDockWidgetArea
        else:
            return QtCore.Qt.RightDockWidgetArea

    # save dock widget size and location
    def onDockLocationChanged(area):
        PREFS.SetInt("dockWidgetArea", int(area.value))
        mw = FreeCADGui.getMainWindow()
        dock = mw.findChild(QtWidgets.QDockWidget, "HelpWidget")
        if dock:
            PREFS.SetBool("dockWidgetFloat", dock.isFloating())
            PREFS.SetInt("dockWidgetWidth", dock.width())
            PREFS.SetInt("dockWidgetHeight", dock.height())

    # a custom page that handles .md links
    class HelpPage(QtWebEngineWidgets.QWebEnginePage):
        def acceptNavigationRequest(self, url, _type, isMainFrame):
            if _type == QtWebEngineWidgets.QWebEnginePage.NavigationTypeLinkClicked:
                show(url.toString(), view=self)
            return super().acceptNavigationRequest(url, _type, isMainFrame)

    mw = FreeCADGui.getMainWindow()
    view = QtWebEngineWidgets.QWebEngineView()
    page = HelpPage(None, view)
    page.setHtml(html, baseUrl=QtCore.QUrl(baseurl))
    view.setPage(page)

    if dialog:
        area = PREFS.GetInt("dockWidgetArea", 2)
        floating = PREFS.GetBool("dockWidgetFloat", True)
        height = PREFS.GetBool("dockWidgetWidth", 200)
        width = PREFS.GetBool("dockWidgetHeight", 300)
        dock = mw.findChild(QtWidgets.QDockWidget, "HelpWidget")
        if not dock:
            dock = QtWidgets.QDockWidget()
            dock.setObjectName("HelpWidget")
            mw.addDockWidget(getDockArea(area), dock)
            dock.setFloating(floating)
            dock.setGeometry(dock.x(), dock.y(), width, height)
            dock.dockLocationChanged.connect(onDockLocationChanged)
        dock.setWidget(view)
        dock.setWindowTitle(title)
        dock.setWindowIcon(QtGui.QIcon(icon))
        dock.show()
    else:
        mdi = mw.findChild(QtWidgets.QMdiArea)
        sw = mdi.addSubWindow(view)
        sw.setWindowTitle(title)
        sw.setWindowIcon(QtGui.QIcon(icon))
        sw.show()
        mdi.setActiveSubWindow(sw)