wikidpad_svn /lib/pwiki/WikiHtmlView.py

Language Python Lines 740
MD5 Hash dae437934baf69b09c9aaf5977076a13 Estimated Cost $12,091 (why?)
Repository https://bitbucket.org/xkjq/wikidpad_svn View Raw File View Project SPDX
  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
## import hotshot
## _prof = hotshot.Profile("hotshot.prf")

import traceback, os, os.path, re

import wx, wx.html

from WikiExceptions import *

from .SystemInfo import isWindows, isOSX

from . import wxHelper
from .wxHelper import getAccelPairFromKeyDown, GUI_ID, wxKeyFunctionSink, \
        appendToMenuByMenuDesc

from .MiscEvent import KeyFunctionSink

from . import StringOps
from StringOps import uniToGui, utf8Enc, utf8Dec, pathEnc, urlFromPathname, \
        urlQuote, pathnameFromUrl, flexibleUrlUnquote
from .Configuration import MIDDLE_MOUSE_CONFIG_TO_TABMODE

from . import OsAbstract

from . import DocPages
from .TempFileSet import TempFileSet

from . import PluginManager

# Try and load the html2 webview renderer
try:
    WikiHtmlViewWK = None
    if wx.version().startswith(("2.9", "3")):
        import WikiHtmlView2
    else:
        WikiHtmlView2 = None

        try:
            import WikiHtmlViewWK
        except:
            WikiHtmlViewWK = None
            import ExceptionLogger
            ExceptionLogger.logOptionalComponentException("Initialize webkit HTML renderer")
            

except:
#         traceback.print_exc()
    WikiHtmlView2 = None
    import ExceptionLogger
    ExceptionLogger.logOptionalComponentException("Initialize webkit HTML2 renderer")



# Try and load Windows IE renderer
if isWindows():
    try:
        import WikiHtmlViewIE
    except:
        import ExceptionLogger
        ExceptionLogger.logOptionalComponentException("Initialize IE HTML renderer")
        WikiHtmlViewIE = None
else:
    WikiHtmlViewIE = None


class LinkConverterForPreview:
    """
    Faked link dictionary for HTML exporter
    """
    def __init__(self, wikiDocument):
        self.wikiDocument = wikiDocument
        
    def getLinkForWikiWord(self, word, default = None):
        if self.wikiDocument.isDefinedWikiLinkTerm(word):
            return u"internaljump:wikipage/%s" % word
        else:
            return default


def createWikiHtmlView(presenter, parent, ID):
    pvRenderer = presenter.getConfig().getint("main", "html_preview_renderer", 0)

    if WikiHtmlViewIE and pvRenderer in (1, 2):
        # Set preview renderer to 0 = Internal
        config = presenter.getConfig()
        config.set("main", "html_preview_renderer", "0")
        config.saveGlobalConfig()
        hvIe = WikiHtmlViewIE.WikiHtmlViewIE(presenter, parent, ID,
                pvRenderer == 2)
        # If no error occurred, set back to previous value
        config.set("main", "html_preview_renderer", str(pvRenderer))
        config.saveGlobalConfig()
        return hvIe
        
    elif WikiHtmlViewWK and pvRenderer == 3:
        return WikiHtmlViewWK.WikiHtmlViewWK(presenter, parent, ID)

    elif WikiHtmlView2 and pvRenderer == 4:
        return WikiHtmlView2.WikiHtmlView2(presenter, parent, ID)

    # Internal preview if nothing else wanted or possible
    return WikiHtmlView(presenter, parent, ID)


class WikiHtmlView(wx.html.HtmlWindow):
    def __init__(self, presenter, parent, ID):
        wx.html.HtmlWindow.__init__(self, parent, ID)
        self.presenter = presenter

        self.presenterListener = wxKeyFunctionSink((
                ("loaded current wiki page", self.onLoadedCurrentWikiPage),
                ("reloaded current doc page", self.onReloadedCurrentPage),
                ("opened wiki", self.onOpenedWiki),
                ("closing current wiki", self.onClosingCurrentWiki)
        ), self.presenter.getMiscEvent())
        
        self.__sinkApp = wxKeyFunctionSink((
                ("options changed", self.onOptionsChanged),
        ), wx.GetApp().getMiscEvent())
        
        self.__sinkDocPage = wxKeyFunctionSink((
                ("updated wiki page", self.onUpdatedWikiPage),
                ("changed live text", self.onChangedLiveText)
        ), self.presenter.getCurrentDocPageProxyEvent())

        self.visible = False
        self.outOfSync = True   # HTML content is out of sync with live content
        self.counterResizeIgnore = 0  # How often to ignore a size event
        self.deferredScrollPos = None  # Used by scrollDeferred()

        self.currentLoadedWikiWord = None

        self.anchor = None  # Name of anchor to jump to when view gets visible
        self.contextHref = None  # Link href on which context menu was opened
        
        # TODO Should be changed to presenter as controller
        self.exporterInstance = PluginManager.getExporterTypeDict(
                self.presenter.getMainControl(), False)[u"html_single"][0]\
                (self.presenter.getMainControl())

        self._DEFAULT_FONT_SIZES = self.presenter.getMainControl().presentationExt.INTHTML_FONTSIZES
        
        # TODO More elegantly
        self.exporterInstance.exportType = u"html_previewWX"
        self.exporterInstance.styleSheet = u""
        self.exporterInstance.tempFileSet = TempFileSet()
        self._updateTempFilePrefPath()

        self.exporterInstance.setWikiDocument(
                self.presenter.getWikiDocument())
        self.exporterInstance.setLinkConverter(
                LinkConverterForPreview(self.presenter.getWikiDocument()))

        wx.EVT_KEY_DOWN(self, self.OnKeyDown)
        wx.EVT_KEY_UP(self, self.OnKeyUp)
        wx.EVT_SIZE(self, self.OnSize)

        wx.EVT_MENU(self, GUI_ID.CMD_CLIPBOARD_COPY, self.OnClipboardCopy)
        wx.EVT_MENU(self, GUI_ID.CMD_SELECT_ALL, lambda evt: self.SelectAll())
        wx.EVT_MENU(self, GUI_ID.CMD_ZOOM_IN, lambda evt: self.addZoom(1))
        wx.EVT_MENU(self, GUI_ID.CMD_ZOOM_OUT, lambda evt: self.addZoom(-1))
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_THIS, self.OnActivateThis)        
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_TAB_THIS,
                self.OnActivateNewTabThis)
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_TAB_BACKGROUND_THIS,
                self.OnActivateNewTabBackgroundThis)
        wx.EVT_MENU(self, GUI_ID.CMD_ACTIVATE_NEW_WINDOW_THIS,
                self.OnActivateNewWindowThis)

        wx.EVT_MENU(self, GUI_ID.CMD_OPEN_CONTAINING_FOLDER_THIS,
                self.OnOpenContainingFolderThis)

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        wx.EVT_LEFT_DCLICK(self, self.OnLeftDClick)
        wx.EVT_MIDDLE_DOWN(self, self.OnMiddleDown)
        wx.EVT_MOUSEWHEEL(self, self.OnMouseWheel)
        wx.EVT_MOTION(self, self.OnMouseMotion)


    def setLayerVisible(self, vis, scName=""):
        """
        Informs the widget if it is really visible on the screen or not
        """
        if not self.visible and vis:
            self.outOfSync = True   # Just to be sure
            self.refresh()
            
        if not vis:
            self.exporterInstance.tempFileSet.clear()

        self.visible = vis



    if isWindows():
        _RE_RIGHT_FILE_URL = re.compile(u"file:/[a-zA-Z]:")
        
        def OnOpeningURL(self, typ, url):
            if url.startswith("file:"):
                if self._RE_RIGHT_FILE_URL.match(url):
                    return wx.html.HTML_OPEN
                # At least under Windows, wxWidgets has another
                # opinion how a local file URL should look like
                # than Python.
                # The same processing is done already by the exporter
                # for WikidPad URL but not for URLs in HTML tags. 
                p = pathnameFromUrl(url)
                url = wx.FileSystem.FileNameToURL(p)
                return url
    
            return wx.html.HTML_OPEN


    def close(self):
        self.Unbind(wx.EVT_SET_FOCUS)
        self.setLayerVisible(False)
        self.presenterListener.disconnect()
        self.__sinkApp.disconnect()
        self.__sinkDocPage.disconnect()


# This doesn't work for wxPython 2.8 and newer, constants are missing
#     _DEFAULT_FONT_SIZES = (wx.html.HTML_FONT_SIZE_1, wx.html.HTML_FONT_SIZE_2, 
#             wx.html.HTML_FONT_SIZE_3, wx.html.HTML_FONT_SIZE_4,
#             wx.html.HTML_FONT_SIZE_5, wx.html.HTML_FONT_SIZE_6,
#             wx.html.HTML_FONT_SIZE_7)

    # These are the Windows sizes
#     if isWindows():
#         _DEFAULT_FONT_SIZES = (7, 8, 10, 12, 16, 22, 30)
#     elif isOSX():
#         _DEFAULT_FONT_SIZES = (9, 12, 14, 18, 24, 30, 36)
#     else:
#         _DEFAULT_FONT_SIZES = (10, 12, 14, 16, 19, 24, 32)




    # For __WXGPE__ (?)
    # _DEFAULT_FONT_SIZES = (6, 7, 8, 9, 10, 12, 14)
    # For others
    # _DEFAULT_FONT_SIZES = (10, 12, 14, 16, 19, 24, 32)


    def refresh(self):
        ## _prof.start()
        
        # Store position of currently displayed page, if any
        if self.currentLoadedWikiWord:
            try:
                prevPage = self.presenter.getWikiDocument().getWikiPage(
                        self.currentLoadedWikiWord)
                prevPage.setPresentation(self.getIntendedViewStart(), 3)
            except WikiWordNotFoundException, e:
                pass

        wikiPage = self.presenter.getDocPage()
        if isinstance(wikiPage,
                (DocPages.DataCarryingPage, DocPages.AliasWikiPage)) and \
                not wikiPage.checkFileSignatureAndMarkDirty():
            # Valid wiki page and invalid signature -> rebuild HTML page
            self.outOfSync = True

        if self.outOfSync:
            self.currentLoadedWikiWord = None
    
            if wikiPage is None:
                return  # TODO Do anything else here?
                
            word = wikiPage.getWikiWord()
            if word is None:
                return  # TODO Do anything else here?

            # Remove previously used temporary files
            self.exporterInstance.tempFileSet.clear()
            self.exporterInstance.buildStyleSheetList()

            self.currentLoadedWikiWord = word
#             content = self.presenter.getLiveText()

            html = self.exporterInstance.exportWikiPageToHtmlString(wikiPage)

            wx.GetApp().getInsertionPluginManager().taskEnd()

    
            # TODO Reset after open wiki
            zoom = self.presenter.getConfig().getint("main", "preview_zoom", 0)
            lx, ly = self.getIntendedViewStart()
            self.SetFonts("", "", [max(s + 2 * zoom, 1)
                    for s in self._DEFAULT_FONT_SIZES])
                    
#             print "-- refresh8", html.encode("mbcs", "ignore")
            self.SetPage(uniToGui(html))
            self.scrollDeferred(lx, ly)

#         traceback.print_stack()
        if self.anchor:   #  and self.HasAnchor(self.anchor):
            if self.HasAnchor(self.anchor):
                self.ScrollToAnchor(self.anchor)
                # Workaround because ScrollToAnchor scrolls too far
                # Here the real scroll position is needed so
                # getIntendedViewStart() is not called
                lx, ly = self.GetViewStart()
                self.scrollDeferred(lx, ly-1)
            else:
                self.scrollDeferred(0, 0)
        elif self.outOfSync:
            lx, ly = wikiPage.getPresentation()[3:5]
            self.scrollDeferred(lx, ly)

        self.anchor = None
        self.outOfSync = False

        ## _prof.stop()


    def gotoAnchor(self, anchor):
        self.anchor = anchor
        if self.visible:
            self.refresh()
            
    
    def GetSelectedText(self):
        return self.SelectionToText()


    def _updateTempFilePrefPath(self):
        wikiDocument = self.presenter.getWikiDocument()

        if wikiDocument is not None:
            self.exporterInstance.tempFileSet.setPreferredPath(
                    wikiDocument.getWikiTempDir())
        else:
            self.exporterInstance.tempFileSet.setPreferredPath(None)


    def onLoadedCurrentWikiPage(self, miscevt):
        self.anchor = miscevt.get("anchor")
        self.outOfSync = True
        if self.visible:
            self.refresh()


    def onReloadedCurrentPage(self, miscevt):
        """
        Called when already loaded page should be loaded again, mainly
        interesting if a link with anchor is activated
        """
        anchor = miscevt.get("anchor")
        if anchor:
            self.gotoAnchor(anchor)
#             self.anchor = anchor
#             if self.visible:
#                 self.refresh()

    def onOpenedWiki(self, miscevt):
        self.currentLoadedWikiWord = None

        self._updateTempFilePrefPath()
        self.exporterInstance.setWikiDocument(
                self.presenter.getWikiDocument())
        self.exporterInstance.setLinkConverter(
                LinkConverterForPreview(self.presenter.getWikiDocument()))

    def onClosingCurrentWiki(self, miscevt):
        if self.currentLoadedWikiWord:
            try:
                prevPage = self.presenter.getWikiDocument().getWikiPage(
                        self.currentLoadedWikiWord)
                prevPage.setPresentation(self.getIntendedViewStart(), 3)
            except WikiWordNotFoundException, e:
                pass

    def onOptionsChanged(self, miscevt):
        self.outOfSync = True
        self._updateTempFilePrefPath()
        if self.visible:
            self.refresh()

    def onUpdatedWikiPage(self, miscevt):
        if self.presenter.getConfig().getboolean("main",
                "html_preview_reduceUpdateHandling", False):
            return

        self.outOfSync = True
        if self.visible:
            self.refresh()
            
    def onChangedLiveText(self, miscevt):
        self.outOfSync = True


    def scrollDeferred(self, lx, ly):
        if self.deferredScrollPos is not None:
            # An unprocessed _scrollAndThaw is in the message queue yet ->
            # just change scrollPos
            self.deferredScrollPos = (lx, ly)
        else:
            # Put new _scrollAndThaw into queue
            self.Freeze()
            self.deferredScrollPos = (lx, ly)
            wx.CallAfter(self._scrollAndThaw)
        
    def _scrollAndThaw(self):
        if wxHelper.isDead(self):
            return
            
        self.Scroll(self.deferredScrollPos[0], self.deferredScrollPos[1])
        self.Thaw()
        self.deferredScrollPos = None
        self.counterResizeIgnore = 0


    def OnSize(self, evt):
        lx, ly = self.getIntendedViewStart()
        self.scrollDeferred(lx, ly)

        evt.Skip()


    def OnSetFocus(self, evt):
        if self.visible:
            self.presenter.makeCurrent()
            self.refresh()

    def OnClipboardCopy(self, evt):
        text = self.SelectionToText()
        if len(text) == 0:
            return

        wxHelper.copyTextToClipboard(text)


    def OnLeftDClick(self, evt):
        pos = self.CalcUnscrolledPosition(evt.GetPosition())
        cell = self.GetInternalRepresentation().FindCellByPos(pos.x, pos.y)
        if cell is not None:
            linkInfo = cell.GetLink()
            if linkInfo is not None:
                evt.Skip()
                return
                
        pres = self.presenter
        mc = pres.getMainControl()
                
        paramDict = {"page": pres.getDocPage(), "presenter": pres,
                "main control": mc}
                
        mc.getUserActionCoord().reactOnUserEvent(
                u"mouse/leftdoubleclick/preview/body", paramDict)

#         self.presenter.switchSubControl("textedit")

        
    def OnMiddleDown(self, evt):
        pos = self.CalcUnscrolledPosition(evt.GetPosition())
        cell = self.GetInternalRepresentation().FindCellByPos(pos.x, pos.y)
        if cell is not None:
            linkInfo = cell.GetLink()
            if linkInfo is not None:
                if not evt.ControlDown():
                    middleConfig = self.presenter.getConfig().getint("main",
                            "mouse_middleButton_withoutCtrl", 2)
                else:
                    middleConfig = self.presenter.getConfig().getint("main",
                            "mouse_middleButton_withCtrl", 3)

                tabMode = MIDDLE_MOUSE_CONFIG_TO_TABMODE[middleConfig]

                self._activateLink(cell.GetLink().GetHref(), tabMode=tabMode)
                return

        evt.Skip()


    def OnLinkClicked(self, linkinfo):
        href = linkinfo.GetHref()
        evt = linkinfo.GetEvent()

        if evt.RightUp():
            self.contextHref = linkinfo.GetHref()
            menu = wx.Menu()
            if href.startswith(u"internaljump:wikipage/"):
                appendToMenuByMenuDesc(menu, _CONTEXT_MENU_INTERNAL_JUMP)
            else:
                appendToMenuByMenuDesc(menu, u"Activate;CMD_ACTIVATE_THIS")
                
                if href.startswith(u"file:") or \
                        href.startswith(u"rel://"):

                    appendToMenuByMenuDesc(menu,
                            u"Open Containing Folder;"
                            u"CMD_OPEN_CONTAINING_FOLDER_THIS")

            self.PopupMenuXY(menu, evt.GetX(), evt.GetY())
        else:
            # Jump to another wiki page
            
            # First check for an anchor. In URLs, anchors are always
            # separated by '#' regardless which character is used
            # in the wiki syntax (normally '!')
            # Now open wiki
            self._activateLink(href, tabMode=0)


    if isOSX():
        def GetViewStart(self):
            result = wx.html.HtmlWindow.GetViewStart(self)
            if isinstance(result, wx.Point):
                return (result.x, result.y)
            else:
                return result


    def getIntendedViewStart(self):
        """
        If a deferred scrolling waits for process, this returns the deferred
        scroll values instead of real view start
        """
        if self.deferredScrollPos is not None:
            return self.deferredScrollPos
        else:
            return tuple(self.GetViewStart())


    def _activateLink(self, href, tabMode=0):
        """
        Called if link was activated by clicking in the context menu, 
        therefore only links starting with "internaljump:wikipage/" can be
        handled.
        tabMode -- 0:Same tab; 2: new tab in foreground; 3: new tab in background
        """
        if href.startswith(u"internaljump:wikipage/"):
            # Jump to another wiki page
            
            # First check for an anchor. In URLs, anchors are always
            # separated by '#' regardless which character is used
            # in the wiki syntax (normally '!')
            try:
                word, anchor = href[22:].split(u"#", 1)
            except ValueError:
                word = href[22:]
                anchor = None

            # open the wiki page
            if tabMode & 2:
                if tabMode == 6:
                    # New Window
                    presenter = self.presenter.getMainControl().\
                            createNewDocPagePresenterTabInNewFrame()
                else:
                    # New tab
                    presenter = self.presenter.getMainControl().\
                            createNewDocPagePresenterTab()
                    presenter.switchSubControl("preview", False)
            else:
                # Same tab
                presenter = self.presenter

            presenter.openWikiPage(word, motionType="child", anchor=anchor)

            if not tabMode & 1:
                # Show in foreground
#                 presenter.switchSubControl("preview", True)
                presenter.getMainControl().getMainAreaPanel().\
                        showPresenter(presenter)
                presenter.SetFocus()
#             else:
#                 presenter.switchSubControl("preview", False)

        elif href == u"internaljump:action/history/back":
            # Go back in history
            self.presenter.getMainControl().goBrowserBack()

        elif href.startswith(u"#"):
            anchor = href[1:]
            if self.HasAnchor(anchor):
                self.ScrollToAnchor(anchor)
                # Workaround because ScrollToAnchor scrolls too far
                # Here the real scroll position is needed so
                # getIntendedViewStart() is not called
                lx, ly = self.GetViewStart()
                self.scrollDeferred(lx, ly-1)
            else:
                self.scrollDeferred(0, 0)
        else:
            self.presenter.getMainControl().launchUrl(href)


    def OnActivateThis(self, evt):
        self._activateLink(self.contextHref, tabMode=0)

    def OnActivateNewTabThis(self, evt):
        self._activateLink(self.contextHref, tabMode=2)

    def OnActivateNewTabBackgroundThis(self, evt):
        self._activateLink(self.contextHref, tabMode=3)

    def OnActivateNewWindowThis(self, evt):
        self._activateLink(self.contextHref, tabMode=6)


    def OnOpenContainingFolderThis(self, evt):
        if not self.contextHref:
            return

        link = self.contextHref

        if link.startswith(u"rel://"):
            link = self.presenter.getWikiDocument().makeRelUrlAbsolute(link)

        if link.startswith(u"file:"):
            try:
                path = os.path.dirname(StringOps.pathnameFromUrl(link))
                if not os.path.exists(StringOps.longPathEnc(path)):
                    self.presenter.displayErrorMessage(
                            _(u"Folder does not exist"))
                    return

                OsAbstract.startFile(self.presenter.getMainControl(),
                        path)
            except IOError:
                pass   # Error message?


    def OnKeyUp(self, evt):
        acc = getAccelPairFromKeyDown(evt)
        if acc == (wx.ACCEL_CTRL, ord('C')): 
            # Consume original clipboard copy function
            pass
        else:
            evt.Skip()

    def addZoom(self, step):
        """
        Modify the zoom setting by step relative to current zoom in
        configuration.
        """
        zoom = self.presenter.getConfig().getint("main", "preview_zoom", 0)
        zoom += step

        self.presenter.getConfig().set("main", "preview_zoom", str(zoom))
        self.outOfSync = True
        self.refresh()


    def OnKeyDown(self, evt):
        acc = getAccelPairFromKeyDown(evt)
        if acc == (wx.ACCEL_CTRL, ord('+')) or \
                acc == (wx.ACCEL_CTRL, wx.WXK_NUMPAD_ADD):
            self.addZoom(1)
        elif acc == (wx.ACCEL_CTRL, ord('-')) or \
                acc == (wx.ACCEL_CTRL, wx.WXK_NUMPAD_SUBTRACT):
            self.addZoom(-1)
        else:
            evt.Skip()


    def OnMouseWheel(self, evt):
        if evt.ControlDown():
            if self.presenter.getConfig().getboolean(
                    "main", "mouse_reverseWheelZoom", False):
                self.addZoom( -(evt.GetWheelRotation() // evt.GetWheelDelta()) )
            else:
                self.addZoom( evt.GetWheelRotation() // evt.GetWheelDelta() )
        else:
            evt.Skip()


    def OnMouseMotion(self, evt):
        evt.Skip()

        pos = self.CalcUnscrolledPosition(evt.GetPosition())
        irep = self.GetInternalRepresentation()
        if irep is None:
            cell = None
        else:
            cell = irep.FindCellByPos(pos.x, pos.y)
        callTip = u""
        status = u""

        if cell is not None:
            linkInfo = cell.GetLink()
            if linkInfo is not None:
                href = linkInfo.GetHref()
                if href.startswith(u"internaljump:wikipage/"):
                    # Jump to another wiki page
                    
                    # First check for an anchor. In URLs, anchors are always
                    # separated by '#' regardless which character is used
                    # in the wiki syntax (normally '!')
                    try:
                        wikiWord, anchor = href[22:].split(u"#", 1)
                        anchor = flexibleUrlUnquote(anchor)
                    except ValueError:
                        wikiWord = href[22:]
                        anchor = None

                    wikiWord = flexibleUrlUnquote(wikiWord)
                    
                    wikiDocument = self.presenter.getWikiDocument()
                    if wikiDocument is None:
                        return
                    wikiWord = wikiDocument.getWikiPageNameForLinkTerm(wikiWord)

                    if wikiWord is not None:
                        propList = wikiDocument.getAttributeTriples(wikiWord,
                                u"short_hint", None)

                        if len(propList) > 0:
                            callTip = propList[-1][2]
                        
                        status = _(u"Link to page: %s") % wikiWord
                else:
                    status = href

        self.presenter.getMainControl().statusBar.SetStatusText(
                        uniToGui(status), 0)

        self.SetToolTipString(callTip)



_CONTEXT_MENU_INTERNAL_JUMP = \
u"""
Activate;CMD_ACTIVATE_THIS
Activate New Tab;CMD_ACTIVATE_NEW_TAB_THIS
Activate New Tab Backgrd.;CMD_ACTIVATE_NEW_TAB_BACKGROUND_THIS
Activate New Window;CMD_ACTIVATE_NEW_WINDOW_THIS
"""


# Entries to support i18n of context menus
if False:
    N_(u"Activate")
    N_(u"Activate New Tab")
    N_(u"Activate New Tab Backgrd.")
    N_(u"Activate New Window")
Back to Top