SF.net SVN: fclient:[769] trunk/fclient/src/fclient
Status: Pre-Alpha
Brought to you by:
jurner
|
From: <jU...@us...> - 2008-07-27 11:32:45
|
Revision: 769
http://fclient.svn.sourceforge.net/fclient/?rev=769&view=rev
Author: jUrner
Date: 2008-07-27 11:32:55 +0000 (Sun, 27 Jul 2008)
Log Message:
-----------
naming
Modified Paths:
--------------
trunk/fclient/src/fclient/fclient.py
Added Paths:
-----------
trunk/fclient/src/fclient/impl/ViewBrowser.py
Removed Paths:
-------------
trunk/fclient/src/fclient/impl/Ui_ViewBrowser.py
Modified: trunk/fclient/src/fclient/fclient.py
===================================================================
--- trunk/fclient/src/fclient/fclient.py 2008-07-27 11:31:20 UTC (rev 768)
+++ trunk/fclient/src/fclient/fclient.py 2008-07-27 11:32:55 UTC (rev 769)
@@ -8,7 +8,7 @@
from .impl.MainWindow import MainWindow
from .impl.View import ViewWidget
-from .impl.Ui_ViewBrowser import ViewBrowserWidget
+from .impl.ViewBrowser import ViewBrowserWidget
from .impl.Ui_ViewConnection import ViewConnectionWidget
from .impl.Ui_ViewDownloads import ViewDownloadsWidget
from .impl.Ui_ViewLogger import ViewLoggerWidget
Deleted: trunk/fclient/src/fclient/impl/Ui_ViewBrowser.py
===================================================================
--- trunk/fclient/src/fclient/impl/Ui_ViewBrowser.py 2008-07-27 11:31:20 UTC (rev 768)
+++ trunk/fclient/src/fclient/impl/Ui_ViewBrowser.py 2008-07-27 11:32:55 UTC (rev 769)
@@ -1,1030 +0,0 @@
-#******************************************************************************************
-#TODO:
-# x. someday. maybe. reimpl to browse via fcp.
-# x. page history is cleared if we get an error on loading a page. reimpl page history?
-# x. back-is-close like behaviour
-# x. backand forward buttons suck somehow. sometimes fwd is enabled even if no fwd is available. reimpl page history?
-# x. save page to disk
-# x. download. idea is to add dls to global download widget and mark them (some color code) as new content.
-# alt would be to to do it firefox like in a separate widget. maybe an option to adjust if browser dls should be
-# persistent or not
-# x. tool buttons do not adjust their size to icon size. maybe it is some global setting via qt-config
-# x. fProxy is a bit tight-lipped when it comes to feedback. no idea
-# x. give feedback on tabs about load / finisched / error. maybe some color code. wait for new QTabWidget features (qt4.5)
-# x. close button on tabs. wait for new QTabWidget features (qt4.5)
-# x. page actions: CopyImageToClipboard,
-# x. when mouse pointer is over an opend image a magnifier cursor appears. no idea how this is handled
-# x. open new tab on tab bar double click. IIRC looks like no way before qt4.5. tabBars are not stretched to fit in qt4.4
-# x. global feedback on statusbar flickers. reason: first label is holds arbitrary length text
-# x. fproxy. "force browser to dl" should we dl it in downloads or store emidiately? no idea
-# x. visiting plugins via fproxy does not work
-# x. real toolbars
-# x. remove host/port from urls?
-# x. browser settings - QWebSettings
-# x. shortcuts
-# x. user staring gui for first time. maybe we should not connext untill the user connects explicitely
-#******************************************************************************************
-"""
-
-@newfield signal: signal, signals
-"""
-from __future__ import absolute_import
-if __name__ == '__main__': # see --> http://bugs.python.org/issue1510172 . works only current dir and below
- import os; __path__ = [os.path.dirname(__file__)]
-
-from PyQt4 import QtCore, QtGui, QtWebKit
-
-from . import config
-
-from .lib import fcp2
-from .lib.qt4ex.lib import tools as qtools
-from .lib.compactpath.qt4 import pathlabelwrap
-
-from . import Ui_DlgPropsBrowserObject
-from . import Ui_DlgDownloadKeyToDisk
-from .tpls.Ui_ViewBrowserWidgetTpl import Ui_ViewBrowserWidget
-#*****************************************************************************************
-#
-#*****************************************************************************************
-class Page(QtWebKit.QWebPage):
- def __init__(self, parent):
- QtWebKit.QWebPage.__init__(self, parent)
-
- #def acceptNavigationRequest(self, frame, request, typeRequest):
- # return True
-
-#*****************************************************************************************
-#
-#*****************************************************************************************
-class Browser(QtWebKit.QWebView):
- """ browser customized for freenet
- """
-
- MaxProgress = 100
-
- def __init__(self, parent=None, userData=None):
- QtWebKit.QWebView.__init__(self, parent)
-
- page = Page(self)
- self.setPage(page)
-
- #NOTE: we store last progress made to set busy cursor accordingly
- self._lastProgress = 0
- self._userData = userData
-
- # connect actions
- self.connect(self, QtCore.SIGNAL('loadStarted()'), self.onLoadStarted)
- self.connect(self, QtCore.SIGNAL('loadProgress(int)'), self.onLoadProgress)
- self.connect(self, QtCore.SIGNAL('loadFinished(bool)'), self.onLoadFinished)
- self.connect(self.pageAction(QtWebKit.QWebPage.Stop), QtCore.SIGNAL('triggered()'), self.onActionStopTriggered)
-
- ################################
- ## methods
- ################################
- #def createWindow(self, typeWindow):
- # pass
-
- def load(self, url):
- self._lastProgress = 0
- return QtWebKit.QWebView.load(self, url)
-
- def setLastStatusMessage(self, qString):
- self._lastStatusMessage = qString
-
- def setUrl(self, url):
- return self.load(url)
-
- def setContents(self, *args):
- """sets the contents of the browser without changing its url"""
- self._lastProgress = 0
- return QtWebKit.QWebView.setContents(self, *args)
-
- def setHtml(self, *args):
- """sets the contents of the browser without changing its url"""
- self._lastProgress = 0
- return QtWebKit.QWebView.setHtm(self, *args)
-
- def setPage(self, page):
- """sets the contents of the browser without changing its url"""
- self._lastProgress = 0
- return QtWebKit.QWebView.setPage(self, page)
-
- def setUserData(self, userData):
- self._userData = userData
-
- def mouseMoveEvent(self, event):
- if self._lastProgress < self.MaxProgress:
- self.setCursor(QtCore.Qt.BusyCursor)
- else:
- QtWebKit.QWebView.mouseMoveEvent(self, event)
-
- def userData(self):
- return self._userData
-
- ###############################
- ## event handlers
- ###############################
- def onActionStopTriggered(self):
- # check wich cursor to set cos we may have busy cursor set
- pt = self.mapFromGlobal(self.cursor().pos()) #TODO: self.mapFromGlobal(self.viewPort().cursor().pos()) ??
- frame = self.page().currentFrame()
- hitTest = frame.hitTestContent(pt)
- #if not hitTest.isNull(): #TODO: looks like hitTest.isNull() alwas returns True
- if hitTest.linkUrl().isValid():
- self.setCursor(QtCore.Qt.PointingHandCursor)
- else:
- self.setCursor(QtCore.Qt.ArrowCursor)
-
- def onLoadStarted(self):
- self._lastProgress = 0
-
- def onLoadProgress(self, n):
- self._lastProgress = n
-
- def onLoadFinished(self):
- self._lastProgress = self.MaxProgress
- self.onActionStopTriggered()
-
- def onPageDownloadRequested(self, networkRequest):
- self.emit(QtCore.SIGNAL('downloadRequested(const QNetworkRequest &)'), networkRequest)
-
-#**********************************************************************************
-#
-#**********************************************************************************
-class BrowserWidgetGlobalFeedback(config.GlobalFeedbackBase):
- """wrapper for global statusbar widgets, menus"""
-
- def __init__(self, parent, idGlobalFeedback):
- config.GlobalFeedbackBase.__init__(self, parent, idGlobalFeedback)
-
- # menus
- self.menus = []
- if self.menuBar is not None and hasattr(parent, 'fcViewObject'):
- menu = QtGui.QMenu(parent.fcViewObject.displayName, self.menuBar)
- parent.populateMenu(menu)
- self.menus.append(menu)
- self.menuBar.addViewMenu(menu)
-
- # status bar widgets
- self.labelStatus = None
- self.progress = None
- self.labelFeedbackWrap = None
- if self.statusBar is not None:
- self.labelStatus = QtGui.QLabel(QtCore.QString(), self.statusBar)
- self.statusBar.addWidget(self.labelStatus)
-
- self.progress = QtGui.QProgressBar(self.statusBar)
- self.progress.setRange(0, Browser.MaxProgress)
- self.progress.setValue(0)
- self.statusBar.addWidget(self.progress)
-
- label = QtGui.QLabel(self.statusBar)
- label.setFrameStyle(QtGui.QLabel.Sunken | QtGui.QLabel.Box)
- self.labelFeedbackWrap = pathlabelwrap.PathLabelWrap(
- label,
- path_module=config.CompactPathFcpKeyModule,
- )
- self.statusBar.addWidget(self.labelFeedbackWrap.label, 1)
-
-
- def setVisible(self, flag):
- if self.menuBar is not None:
- for menu in self.menus:
- menu.children()[0].setVisible(flag)
- if self.statusBar is not None:
- self.progress.setVisible(flag)
- self.labelStatus.setVisible(flag)
- self.labelFeedbackWrap.label.setVisible(flag)
-
- def setProgress(self, n):
- if self.progress is not None:
- self.progress.setValue(n)
-
- def setStatusMessage(self, qString):
- if self.labelStatus is not None:
- self.labelStatus.setText(qString)
-
- def setFeedback(self, qString):
- if self.labelFeedbackWrap is not None:
- self.labelFeedbackWrap.setPath(unicode(qString))
-
-
-class BrowserWidgetViewObject(config.ViewObject):
-
- def __init__(self, parent):
- config.ViewObject. __init__(self, parent)
-
- self.name=parent.objectName()
- self.displayName=self.trUtf8('Browser')
- self.icon=QtGui.QIcon()
-
-
-class BrowserWidgetSettings(config.SettingsBase):
- _key_ = config.IdViewBrowserWidget
- _settings_ = (
- ('OpenLinksInNewTab', 'Bool', False, config.SettingScopeUser),
- ('OpenAddressBarInNewTab', 'Bool', False, config.SettingScopeUser),
- ('OpenBookmarksInNewTab', 'Bool', False, config.SettingScopeUser),
- ('OpenHomePageOnNewTabCreated', 'Bool', False, config.SettingScopeUser),
- ('BackIsClose', 'Bool', False, config.SettingScopeUser), #TODO: not implemented
- ('HomePage', 'String', QtCore.QString(), config.SettingScopeUser),
- ('IconSize', 'UInt', 32, config.SettingScopeUser),
- ('IconTheme', 'String', QtCore.QString('crystal'), config.SettingScopeUser),
- ('AutoLoadImages', 'Bool', True, config.SettingScopeUser), #TODO: not yet implemented
- ('MaxTabText', 'UInt', 20, config.SettingScopeUser), #NOTE: make shure Max >= Min and Max and Min > 0
- ('MinTabText', 'UInt', 7, config.SettingScopeUser),
- )
-
- def setValues(self, **kws):
- autoLoadImages = kws.get('AutoLoadImages', None)
- if autoLoadImages is not None:
- browserWidget = self.parent()
- tabWidget = browserWidget.controlById(browserWidget.IdTabBrowsers)
- for i in xrange(tabWidget.count()):
- browser = tabWidget.widget(i)
- settings = browser.settings()
- settings.setAttribute(settings.AutoLoadImages, autoLoadImages)
- config.SettingsBase.setValues(self, **kws)
-
- #backIsClose = kws.get('BackIsClose', None)
- #if backIsClose is not None:
- # self.parent()._adjustBackIsClose()
-
-
-
-class BrowserWidgetActions(config.ActionsBase):
-
- def __init__(self, parent):
- config.ActionsBase.__init__(self, parent)
-
- iconSize = parent.fcSettings.value('IconSize')
- iconTheme = parent.fcSettings.value('IconTheme')
-
- self.action(
- name='ActionCloseCurrentTab',
- text=self.trUtf8('Close ¤t tab'),
- trigger=parent.onCloseCurrentTab,
- )
- self.action( # context menu only
- name='ActionCloseBrowserUnderMouse',
- text=self.trUtf8('&Close tab'),
- trigger=None,
- )
- self.action(
- name='ActionCloseAllTabs',
- text=self.trUtf8('Close &all tabs'),
- trigger=parent.onCloseAllTabs,
- )
- self.action(
- name='ActionOpenNewTab',
- text=self.trUtf8('Open &new tab'),
- trigger=parent.onOpenNewTab,
- )
- self.action(
- name='ActionGoToFProxy',
- text=self.trUtf8('Go to f&Proxy homepage'),
- trigger=parent.onGoToFProxy,
- )
- self.action(
- name='ActionGoToHomePage',
- text=self.trUtf8('Go to &homepage'),
- trigger=parent.onGoToHomePage,
- )
- self.action(
- name='ActionObjectProperties',
- text=self.trUtf8('Properties..'),
- trigger=None,
- )
- self.action(
- name='ActionZoomIn',
- text=self.trUtf8('Zoom in'),
- trigger=parent.onZoomIn,
- )
- self.action(
- name='ActionZoomOut',
- text=self.trUtf8('Zoom out'),
- trigger=parent.onZoomOut,
- )
-
- # default browser actions
- self.action(
- name='ActionBack',
- text=self.trUtf8('Back'),
- trigger=None,
- isEnabled=False,
- icon=config.resources.getIcon('back', iconSize, iconTheme=iconTheme),
- userData=(None, None),
- )
- self.action(
- name='ActionForward',
- text=self.trUtf8('Forward'),
- trigger=None,
- isEnabled=False,
- icon=config.resources.getIcon('forward', iconSize, iconTheme=iconTheme),
- userData=(None, None),
- )
- self.action(
- name='ActionReload',
- text=self.trUtf8('Reload'),
- trigger=None,
- isEnabled=False,
- icon=config.resources.getIcon('reload_page', iconSize, iconTheme=iconTheme),
- userData=(None, None),
- )
- self.action(
- name='ActionStop',
- text=self.trUtf8('Stop'),
- trigger=None,
- isEnabled=False,
- icon=config.resources.getIcon('stop', iconSize, iconTheme=iconTheme),
- userData=(None, None),
- )
-
- self.action(
- name='ActionBackIsClose',
- text=self.trUtf8('Back is close'),
- icon=config.resources.getIcon('button_cancel', iconSize, iconTheme=iconTheme),
- trigger=None,
- )
-
- # search actions
- self.action(
- parent=parent,
- name='ActionSearch',
- text=self.trUtf8('Search'),
- shortcut=QtGui.QKeySequence(self.trUtf8('Ctrl+F')),
- trigger=parent.onSearch,
- )
-
- def intertwineBrowserActions(self, browser=None):
- """intertwines Browser actions with BrowserWidget actions
- @note: call everytime the current browser changes
- """
- actions = (
- ('ActionBack', QtWebKit.QWebPage.Back),
- ('ActionForward', QtWebKit.QWebPage.Forward),
- ('ActionReload', QtWebKit.QWebPage.Reload),
- ('ActionStop', QtWebKit.QWebPage.Stop),
- )
- for actionName, pageAction in actions:
- myPageAction = self[actionName]
- newPageAction = None if browser is None else browser.pageAction(pageAction)
- oldPageAction, cb = myPageAction.userData()
-
- if oldPageAction is not None:
- myPageAction.disconnect(oldPageAction, QtCore.SIGNAL('changed()'), cb)
- oldPageAction.disconnect(myPageAction, QtCore.SIGNAL('triggered()'), oldPageAction.trigger)
-
- if newPageAction is None:
- myPageAction.setUserData((None, None))
- myPageAction.setEnabled(False)
- else:
- def onActionChanged(browser=browser, myPageAction=myPageAction, browserPageAction=newPageAction):
- myPageAction.setEnabled(browserPageAction.isEnabled())
-
- myPageAction.setEnabled(newPageAction.isEnabled())
- myPageAction.setUserData((newPageAction, onActionChanged))
- myPageAction.connect(newPageAction, QtCore.SIGNAL('changed()'), onActionChanged)
- newPageAction.connect(myPageAction, QtCore.SIGNAL('triggered()'), newPageAction.trigger)
-
-
-class LastBrowserState(object):
- """records the last known state browser"""
-
- __slots__ = ('icon', 'progress', 'statusMessage', 'title', 'url')
-
- def __init__(self, icon=None, progress=0, statusMessage=None, title=None, url=None):
- self.progress = 0
- self.icon = tCore.QIcon() if icon is None else icon
- self.statusMessage = QtCore.QString() if statusMessage is None else statusMessage
- self.title = QtCore.QString() if title is None else title
- #NOTE: opening a browser in a new tab may take a while to load.
- # self.url() will return '' untill the page is found, so we handle
- # it ourself and keep track of the last known url in self._lastUrl
- # to give feedback to the user on the navbar. downside is we have
- # to reimplement contextMenuEvent() :-(
- self.url = QtCore.QUrl() if url is None else url
-
-#**********************************************************************************
-#
-#**********************************************************************************
-#TODO: strip host:port on address bar?
-#TODO: rename home page to start page
-class ViewBrowserWidget(QtGui.QWidget, Ui_ViewBrowserWidget):
-
- IdTabBrowsers = 'tabBrowsers'
- IdFrameTools = 'frameTools'
- IdFrameAddressBar = 'frameAddressBar'
- IdEdAddressBar = 'edAddressBar'
-
- IdBtBack = 'btBack'
- IdBtForward = 'btForward'
- IdBtReload = 'btReload'
- IdBtStop = 'btStop'
-
- IdFrameSearch = 'frameSearch'
- IdEdSearch = 'edSearch'
- IdBtSearchUpwards = 'btSearchUpwards'
- IdBtSearchDownwards = 'btSearchDownwards'
- IdCkSearchCaseSensitive = 'ckSearchCaseSensitive'
-
- ForcedMinBrowserTabText = 5 # forced minimum number of chars on browser tabBar
-
- def __init__(self, parent, idGlobalFeedback=config.IdMainWindow):
- QtGui.QWidget.__init__(self, parent)
-
- self.setupUi(self)
- config.ObjectRegistry.register(self)
-
- self._initialConfigDataArrived = False
-
- self.fcSettings = BrowserWidgetSettings(self).restore()
- self.fcActions = BrowserWidgetActions(self)
- self.fcViewObject = BrowserWidgetViewObject(self)
- self.fcGlobalFeedback = BrowserWidgetGlobalFeedback(self, idGlobalFeedback)
-
- # setup tab bar
- tabWidget = self.controlById(self.IdTabBrowsers)
- tabWidget.clear()
- tabWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
- self.connect(tabWidget, QtCore.SIGNAL('currentChanged(int)'), self.onTabCurrentChanged)
- self.connect(tabWidget, QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'), self.onTabContextMenuEvent)
-
- # setup addressbar
- addressbar = self.controlById(self.IdEdAddressBar)
- self.connect(addressbar, QtCore.SIGNAL('returnPressed()'), self.onNavBarReturnPressed)
-
- # setup tool buttons
- self.controlById(self.IdBtBack).setDefaultAction(self.fcActions['ActionBack'])
- self.controlById(self.IdBtForward).setDefaultAction(self.fcActions['ActionForward'])
- self.controlById(self.IdBtReload).setDefaultAction(self.fcActions['ActionReload'])
- self.controlById(self.IdBtStop).setDefaultAction(self.fcActions['ActionStop'])
-
- # setupp search bar
- bt = self.controlById(self.IdBtSearchUpwards)
- self.connect(bt, QtCore.SIGNAL('clicked()'), self.onSearchUpwards)
- bt = self.controlById(self.IdBtSearchDownwards)
- self.connect(bt, QtCore.SIGNAL('clicked()'), self.onSearchDownwards)
- ed = self.controlById(self.IdEdSearch)
- self.connect(ed, QtCore.SIGNAL('returnPressed()'), self.onSearchDownwards)
- frameSearch = self.controlById(self.IdFrameSearch)
- frameSearch.setVisible(False)
-
- # fire up a new broser to make a start
- self.newBrowser(title=self.trUtf8('Waiting for fproxy'))
- self.fcActions['ActionGoToHomePage'].trigger()
-
- #########################################
- ## private methods
- #########################################
- #NOTE: to reduce flicker set min size to max size
- def _adjustTabText(self, qString):
- maxTabText = self.fcSettings.value('MaxTabText')
- minTabText = self.fcSettings.value('MinTabText')
- ellipsis = self.trUtf8('..')
-
- if minTabText < self.ForcedMinBrowserTabText:
- minTabText = self.ForcedMinBrowserTabText
- self.fcSettings.setValues(MinTabText=minTabText)
- if maxTabText < self.ForcedMinBrowserTabText:
- maxTabText = self.ForcedMinBrowserTabText
- self.fcSettings.setValues(MaxTabText=maxTabText)
- if minTabText > maxTabText:
- minTabText = maxTabText
- self.fcSettings.setValues(MinTabText=maxTabText)
-
- if qString.count() < minTabText:
- qString = qString.append('\x20' * (minTabText - qString.count()))
- else:
- if maxTabText < self.ForcedMinBrowserTabText:
- maxTabText = sminTabText
- qString = qtools.truncateString(maxTabText, qString, ellipsis)
- return qString
-
- def _downloadImageToDisk(self, hitTestResult):
- px = hitTestResult.pixmap()
- if px.isNull():
- return False
-
- key = config.qStringToFcpKey(hitTestResult.imageUrl().toString())
- if key is None:
- return False
-
- # thow a dialog box at the user to select a filename
- # ..qt seems to place the filename part as suggestion into the filename box. so try it
- caption = config.FclientAppName + self.trUtf8(' - Save Image To..')
- directory = unicode(config.settings.value('DownloadDir'))
- fileName = unicode(config.guessFileNameFromKey(key, default=QtCore.QString('')))
-
- if directory and fileName:
- directory = os.path.join(directory, fileName)
- elif not directory:
- directory = fileName
- filePath = QtGui.QFileDialog.getSaveFileName(self, caption, directory)
-
- if filePath:
- filePath= unicode(filePath)
- if os.path.exists(filePath):
- try:
- os.remove(filePath)
- except Exception, details:
- QtGui.QMessageBox.critical(
- self,
- caption,
- self.trUtf8('Could not remove file'), #NOTE: no details please, may contain arbitrary lenght filepath
- )
- return False
- px.save(filePath)
- return True
-
- def _downloadKeyToDisk(self, qUrl):
- """
- @return: (bool) False if the key in the url is invalid, True otherwise
- """
- fcpKey = config.qStringToFcpKey(QtCore.QString(qUrl.encodedPath()))
- if fcpKey is not None:
- dlg = Ui_DlgDownloadKeyToDisk.DownloadKeyToDiskDlg(self, fcpKey=fcpKey)
- if dlg.exec_() == dlg.Accepted:
- filePath = dlg.filePath()
- downloadsWidget = config.ObjectRegistry.get(config.IdViewCDownloadsWidget, None)
- if downloadsWidget is None:
- raise ValueError('no downloads widget found')
- downloadsWidget.downloadFile(
- fcpKey,
- filePath,
- persistence=fcp2.ConstPersistence.Forever,
- handleFilenameCollision=True,
-
- )
- return True
- return False
-
- #########################################
- ## methods
- #########################################
- def controlById(self, idControl):
- return getattr(self, idControl)
-
- def currentBrowser(self):
- """returns the current browser or None"""
- tabWidget = self.controlById(self.IdTabBrowsers)
- return tabWidget.currentWidget()
-
- def load(self, url, force=False, browser=None):
- """loads an url in the current browser. if there is no current browser, a new browser is created
- @param force: (bool) if True, a new browser is opend if there is no browser available
- @param browser: browser to load the url in or None to use the current browser
- @return: (bool)
- """
- browser = self.currentBrowser() if browser is None else browser
- tabWidget = self.controlById(self.IdTabBrowsers)
- addressBar = self.controlById(self.IdEdAddressBar)
- url = QtCore.QUrl(url)
-
- # check if we have a browser at hand
- if force and browser is None:
- browser = self.newBrowser()
- if browser is None:
- return False
-
- # load url
- url.setScheme('http')
- url.setHost(config.settings.value('FproxyConnectionHost'))
- url.setPort(config.settings.value('FproxyConnectionPort'))
- tabWidget.setTabText(tabWidget.indexOf(browser), self._adjustTabText(self.trUtf8('Loading')))
- addressBar.setText(url.toString())
- lastBrowserState = browser.userData()
- lastBrowserState.url = url
- browser.load(url)
- return True
-
- def newBrowser(self, title=''):
- """opens a browser in a new tab"""
- tabWidget = self.controlById(self.IdTabBrowsers)
- browser = Browser(self)
- page = browser.page()
- settings = browser.settings()
- title = QtCore.QString(title)
-
- # attatch browser state information
- lastBrowserState = LastBrowserState(
- icon=browser.icon(),
- statusMessage=self.trUtf8('Waiting'),
- )
- browser.setUserData(lastBrowserState)
-
- # customize browser
- browser.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
- settings.setAttribute(settings.DeveloperExtrasEnabled, False)
- settings.setAttribute(settings.JavaEnabled, False)
- settings.setAttribute(settings.JavascriptEnabled, False)
- settings.setAttribute(settings.JavascriptCanOpenWindows, False)
- settings.setAttribute(settings.JavascriptCanAccessClipboard, False)
- settings.setAttribute(settings.PluginsEnabled, False)
- settings.setAttribute(settings.AutoLoadImages, self.fcSettings.value('AutoLoadImages'))
-
- # connect browser signals
- self.connect(browser, QtCore.SIGNAL('loadStarted()'), self.onBrowserLoadStarted)
- self.connect(browser, QtCore.SIGNAL('loadProgress(int)'), self.onBrowserLoadProgress)
- self.connect(browser, QtCore.SIGNAL('loadFinished(bool)'), self.onBrowserLoadFinished)
- self.connect(browser, QtCore.SIGNAL('iconChanged()'), self.onBrowserIconChanged)
- self.connect(browser, QtCore.SIGNAL('statusBarMessage(const QString &)'), self.onBrowserStatusBarMessage)
- self.connect(browser, QtCore.SIGNAL('titleChanged(const QString &)'), self.onBrowserTitleChanged)
- self.connect(browser, QtCore.SIGNAL('urlChanged(const QUrl &)'), self.onBrowserUrlChanged)
- self.connect(browser, QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'), self.onBrowserCustomContextMenuRequested)
- self.connect(browser, QtCore.SIGNAL('linkClicked(const QUrl &)'), self.onBrowserLinkClicked)
-
- # adjust browser actions
- act = browser.pageAction(page.OpenLinkInNewWindow)
- act.setText(self.trUtf8('Open page in new tab'))
- act = browser.pageAction(page.OpenImageInNewWindow)
- act.setText(self.trUtf8('Open image in new tab'))
- act = browser.pageAction(page.OpenFrameInNewWindow)
- act.setText(self.trUtf8('Open frame in new tab'))
-
- # customize page
- page.setLinkDelegationPolicy(page.DelegateAllLinks)
-
- # connect page signals
- self.connect(page, QtCore.SIGNAL('linkHovered(const QString &, const QString &, const QString &)'), self.onPageLinkHovered)
-
- tabWidget.addTab(browser, self._adjustTabText(title))
- if tabWidget.currentWidget() == browser:
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
- return browser
-
- #TODO: rework. we need more then one menu
- def populateMenu(self, menu):
- menu.addAction(self.fcActions['ActionGoToFProxy'])
- menu.addAction(self.fcActions['ActionGoToHomePage'])
- menu.addAction(self.fcActions['ActionCloseCurrentTab'])
- menu.addAction(self.fcActions['ActionCloseAllTabs'])
- menu.addAction(self.fcActions['ActionOpenNewTab'])
- menu.addAction(self.fcActions['ActionZoomIn'])
- menu.addAction(self.fcActions['ActionZoomOut'])
- menu.addAction(self.fcActions['ActionSearch'])
- return menu
-
- #########################################
- ## overwritten events
- #########################################
- def closeEvent(self):
- self.viewClose()
-
- def hideEvent(self, event):
- self.fcGlobalFeedback.setVisible(False)
-
- def showEvent(self, event):
- self.fcGlobalFeedback.setVisible(True)
-
- def viewClose(self):
- pass
-
- #########################################
- ## event handlers
- #########################################
- #TODO: actions need some comb over
- def onBrowserCustomContextMenuRequested(self, pt):
- browser = self.sender()
- frame = browser.page().currentFrame()
- page = browser.page()
- hitTestResult = frame.hitTestContent(pt)
-
- #if not hitTest.isNull(): #TODO: looks like hitTest.isNull() alwas returns True
-
- menu = QtGui.QMenu()
-
- menu.addAction(browser.pageAction(page.OpenLink))
- menu.addAction(browser.pageAction(page.OpenLinkInNewWindow))
- menu.addAction(browser.pageAction(page.CopyLinkToClipboard))
- menu.addAction(browser.pageAction(page.DownloadLinkToDisk))
-
- menu.addSeparator()
- menu.addAction(browser.pageAction(page.OpenImageInNewWindow))
- menu.addAction(browser.pageAction(page.CopyImageToClipboard))
- menu.addAction(browser.pageAction(page.DownloadImageToDisk))
-
- menu.addSeparator()
- menu.addAction(browser.pageAction(page.OpenFrameInNewWindow))
-
- menu.addSeparator()
- menu.addAction(browser.pageAction(page.Copy))
- menu.addAction(self.fcActions['ActionObjectProperties'])
-
- action = menu.exec_(pt)
-
- if action == browser.pageAction(page.OpenLinkInNewWindow):
- browser = self.newBrowser(title=self.trUtf8('Loading'))
- self.load(hitTestResult.linkUrl(), browser=browser)
- elif action == browser.pageAction(page.OpenImageInNewWindow):
- browser = self.newBrowser(title=self.trUtf8('Loading'))
- self.load(hitTestResult.imageUrl(), browser=browser)
- elif action == browser.pageAction(page.OpenFrameInNewWindow):
- browser = self.newBrowser(title=self.trUtf8('Loading'))
- self.load(hitTestResult.frame().url(), browser=browser)
- elif action == browser.pageAction(page.DownloadImageToDisk):
- self._downloadImageToDisk(hitTestResult)
- elif action == browser.pageAction(page.DownloadLinkToDisk):
- self._downloadKeyToDisk(hitTestResult.linkUrl())
- elif action == self.fcActions['ActionObjectProperties']:
- dlg = Ui_DlgPropsBrowserObject.PropsBrowserObjectDlg(self, hitTestResult=hitTestResult)
- if dlg.exec_() == dlg.Accepted:
- pass
-
- #TODO: nav buttons seem to get confused on error
- def onBrowserLoadFinished(self, ok):
- browser = self.sender()
- lastBrowserState = browser.userData()
- tabWidget = self.controlById(self.IdTabBrowsers)
-
- lastBrowserState.progress = Browser.MaxProgress
- if ok:
- lastBrowserState.statusMessage = self.trUtf8('Complete')
- if lastBrowserState.title.isEmpty():
- tabWidget.setTabText(tabWidget.indexOf(browser), self._adjustTabText(self.trUtf8('Complete')))
- if browser == self.currentBrowser():
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
- else:
- # something went wrong. most likely fProxy can not be reached
- lastBrowserState.statusMessage = self.trUtf8('Error')
- tabWidget.setTabText(tabWidget.indexOf(browser), self._adjustTabText(self.trUtf8('Error')))
- if browser == self.currentBrowser():
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
-
- settings = browser.settings()
- settings.setAttribute(settings.JavascriptEnabled, True)
- try:
- p = (
- '<h3>%s</h3>' % self.trUtf8('Error: request failed'),
- self.trUtf8('Possible reasons:'),
- '<ul>',
- '<li>',
- self.trUtf8('fProxy can not be reached. check if fproxy is running and check your node config if fproxy host and port are set'),
- '</li>',
- '<li>',
- self.trUtf8('maybe your os can not deal with ipv6 addresses. make shure fProxy is reachable via an ipv4 address'),
- '</li>',
- '<li>',
- self.trUtf8('there is no problem. try it again..'),
- '</li>',
- '</ul>'
- )
- p = ''.join([unicode(i) for i in p])
- browser.page().mainFrame().evaluateJavaScript('document.write("<div>%s</div>");' % p)
- finally:
- settings.setAttribute(settings.JavascriptEnabled, False)
-
- def onBrowserIconChanged(self, qIcon):
- browser = self.sender()
- qIcon = QtCore.QIcon(qIcon) # copy it - qt nukes it on return
-
- lastBrowserState = browser.userData()
- if not qIcon.isNull():
- lastBrowserState = qIcon
- self.tabWidget.setTabIcon(i, lastBrowserState.icon)
-
- def onBrowserLoadProgress(self, n):
- browser = self.sender()
- lastBrowserState = browser.userData()
-
- lastBrowserState.progress = n
- if self.sender() == self.currentBrowser():
- self.fcGlobalFeedback.setProgress(n)
-
- def onBrowserLinkClicked(self, qUrl):
- browser = self.sender()
- qUrl = QtCore.QUrl(qUrl)
- query = unicode(qUrl.encodedQuery())
-
- if query.lower() == 'forcedownload':
- if not self._downloadKeyToDisk(qUrl):
- self.fcGlobalFeedback.setFeedback(self.trUtf8('Invalid key!'))
- else: # assume fproxy is doing the right thing
- if self.fcSettings.value('OpenLinksInNewTab'):
- browser = self.newBrowser(title=self.trUtf8('Loading'))
- self.load(qUrl, browser=browser)
-
- def onBrowserLoadStarted(self):
- browser = self.sender()
- lastBrowserState = browser.userData()
- tabWidget = self.controlById(self.IdTabBrowsers)
-
- lastBrowserState.statusMessage = self.trUtf8('Loading')
- tabWidget.setTabText(tabWidget.indexOf(browser), self._adjustTabText(self.trUtf8('Loading')))
- if browser == self.currentBrowser():
- self.fcGlobalFeedback.setProgress(0)
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
-
- def onBrowserStatusBarMessage(self, qString):
- browser = self.sender()
- qString = QtCore.QString(qString) # copy it - qt nukes it on return
-
- lastBrowserState = browser.userData()
- if not qString.isEmpty():
- lastBrowserState.statusMessage = qString
- if browser == self.currentBrowser():
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
-
- def onBrowserTitleChanged(self, qString):
- browser = self.sender()
- qString = QtCore.QString(qString) # copy it - qt nukes it on return
- maxTabText = self.fcSettings.value('MaxTabText')
- tabWidget = self.controlById(self.IdTabBrowsers)
- lastBrowserState = browser.userData()
- if not qString.isEmpty():
- lastBrowserState.title = qString
- tabWidget.setTabText(tabWidget.indexOf(browser), self._adjustTabText( lastBrowserState.title))
-
- def onBrowserUrlChanged(self, qUrl):
- browser = self.sender()
- qUrl = QtCore.QUrl(qUrl) # copy it - qt nukes it on return
-
- lastBrowserState = browser.userData()
- if qUrl.isValid():
- lastBrowserState.url = qUrl
- addressbar = self.controlById(self.IdEdAddressBar)
- addressbar.setText(lastBrowserState.url.toString())
-
- def onCloseAllTabs(self, action):
- # have to do it by hand to reset [BackIsClose]
- tabWidget = self.controlById(self.IdTabBrowsers)
- tabWidget.clear()
- self.fcActions.intertwineBrowserActions(self.currentBrowser())
-
- def onCloseCurrentTab(self, action):
- tabWidget = self.controlById(self.IdTabBrowsers)
- i = tabWidget.currentIndex()
- if i > -1:
- tabWidget.removeTab(i)
- self.fcActions.intertwineBrowserActions(self.currentBrowser())
-
- #TODO: open in new tab option?
- def onGoToFProxy(self, action):
- url = QtCore.QUrl()
- self.load(url, force=True)
-
- #TODO: open in new tab option?
- def onGoToHomePage(self, action):
- home = self.fcSettings.value('HomePage')
- qUrl = QtCore.QUrl(home)
- self.load(qUrl, force=True)
-
- def onNavBarReturnPressed(self):
- text = self.controlById(self.IdEdAddressBar).text()
- if text.isEmpty():
- return
- qUrl = QtCore.QUrl(text)
- browser = self.currentBrowser()
- if browser is None or self.fcSettings.value('OpenAddressBarInNewTab'):
- browser = self.newBrowser(title=self.trUtf8('Loading'))
- self.load(qUrl, browser=browser)
-
- #TODO: we get no load progress feedback here?
- #TODO: more choices for page to load
- def onOpenNewTab(self, action):
- browser = self.newBrowser(title=self.trUtf8('Empty'))
- if self.fcSettings.value('OpenHomePageOnNewTabCreated'):
- homePage = self.fcSettings.value('HomePage')
- self.load(QtCore.QUrl(homePage), browser=browser)
-
- def onPageLinkHovered(self, link, title, textContent):
- self.fcGlobalFeedback.setFeedback(QtCore.QString(link))
-
- def onPageActionBackChanged(self):
- act = self.sender()
- browser = self.currentBrowser()
- if browser is not None and act is browser.pageAction(browser.page().Back):
- self._adjustBackIsClose()
-
- def onSearch(self, action):
- frameSearch = self.controlById(self.IdFrameSearch)
- frameSearch.setVisible(not frameSearch.isVisible())
-
- def onSearchDownwards(self):
- browser = self.currentBrowser()
- if browser is not None:
- page = browser.page()
- ed = self.controlById(self.IdEdSearch)
- ck = self.controlById(self.IdCkSearchCaseSensitive)
- flags = page.FindWrapsAroundDocument
- if ck.checkState() == QtCore.Qt.Checked:
- flags |= page.FindCaseSensitively
- browser.findText(ed.text(), flags)
-
- def onSearchUpwards(self):
- browser = self.currentBrowser()
- if browser is not None:
- page = browser.page()
- ed = self.controlById(self.IdEdSearch)
- ck = self.controlById(self.IdCkSearchCaseSensitive)
- flags = page.FindWrapsAroundDocument | page.FindBackward
- if ck.checkState() == QtCore.Qt.Checked:
- flags |= page.FindCaseSensitively
- browser.findText(ed.text(), flags)
-
- def onTabContextMenuEvent(self, pt):
- menu = QtGui.QMenu()
- tabWidget = self.controlById(self.IdTabBrowsers)
- pt = tabWidget.mapToGlobal(pt)
- pt2 = tabWidget.tabBar().mapFromGlobal(pt)
- i = tabWidget.tabBar().tabAt(pt2)
- # setup menu
- actCloseBrowserUnderMouse = self.fcActions['ActionCloseBrowserUnderMouse']
- actCloseBrowserUnderMouse.setEnabled(i >-1)
- menu.addAction(actCloseBrowserUnderMouse)
- menu.addAction(self.fcActions['ActionCloseAllTabs'])
- act = menu.exec_(pt)
- if act == actCloseBrowserUnderMouse:
- tabWidget.removeTab(i)
- self.fcActions.intertwineBrowserActions(self.currentBrowser())
-
- def onTabCurrentChanged(self, i):
- tabWidget = self.controlById(self.IdTabBrowsers)
- browser = tabWidget.widget(i)
-
- self.fcActions.intertwineBrowserActions(browser)
- if browser is not None:
- lastBrowserState = browser.userData()
- addressBar = self.controlById(self.IdEdAddressBar)
-
- # update status info
- addressBar.setText(lastBrowserState.url.toString())
- self.fcGlobalFeedback.setStatusMessage(lastBrowserState.statusMessage)
- self.fcGlobalFeedback.setProgress(lastBrowserState.progress)
-
- #TODO: enable/disable, but no view gives non feedback on max/min zoom
- def onZoomIn(self, action):
- browser = self.currentBrowser()
- if browser is not None:
- oldMultiplier = browser.textSizeMultiplier()
- browser.setTextSizeMultiplier(browser.textSizeMultiplier() + 0.2)
- if browser.textSizeMultiplier() <= oldMultiplier:
- menu.addAction(self.fcActions['ActionZoomIn']).setEnabled(False)
-
- def onZoomOut(self, action):
- browser = self.currentBrowser()
- if browser is not None:
- oldMultiplier = browser.textSizeMultiplier()
- browser.setTextSizeMultiplier(browser.textSizeMultiplier() - 0.2)
- if browser.textSizeMultiplier() >= oldMultiplier:
- menu.addAction(self.fcActions['ActionZoomOut']).setEnabled(False)
-
-#**********************************************************************************
-#
-#**********************************************************************************
-if __name__ == '__main__':
- import sys
- from .Ui_ViewLogger import ViewLoggerWidget
- from .MainWindow import MainWindow
- from .View import ViewWidget
- from .Ui_ViewConnection import ViewConnectionWidget
- from .Ui_ViewDownloads import ViewDownloadsWidget
-
- app = QtGui.QApplication(sys.argv)
-
- mainWindow = MainWindow()
- viewWidget = ViewWidget(mainWindow)
- mainWindow.setCentralWidget(viewWidget)
-
- browserWidget = ViewBrowserWidget(mainWindow)
- viewWidget.addTopViews(
- ViewConnectionWidget(mainWindow),
- browserWidget,
- ViewDownloadsWidget(mainWindow),
- )
- viewWidget.addBottomViews(ViewLoggerWidget(mainWindow))
-
- mainWindow.show()
- res = app.exec_()
- sys.exit(res)
-
-#**********************************************************************************
-#
-#**********************************************************************************
-## looks we could serve pages via fcp, bypassing fproxy
-## no reason to do so..
-##
-##class NetworkAccessManager(QtNetwork.QNetworkAccessManager):
-##
-## def __init__(self, parent):
-## QtNetwork.QNetworkAccessManager.__init__(self, parent)
-##
-## def createRequest(self, operation, request, outgoingData):
-## print 'createRequest', request.url()
-## reply = QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, outgoingData)
-## #TODO: implement QNetworkReply()
-## return reply
-##
-##
-##class Browser(QtWebKit.QWebView):
-##
-##def __init__(self, browserWidget):
-## QtWebKit.QWebView.__init__(self, browserWidget)
-##
-## self.nam = NetworkAccessManager(self)
-## self.page().setNetworkAccessManager(self.nam)
-##
-#**********************************************************************************
-#
-#**********************************************************************************
-
\ No newline at end of file
Added: trunk/fclient/src/fclient/impl/ViewBrowser.py
===================================================================
--- trunk/fclient/src/fclient/impl/ViewBrowser.py (rev 0)
+++ trunk/fclient/src/fclient/impl/ViewBrowser.py 2008-07-27 11:32:55 UTC (rev 769)
@@ -0,0 +1,1030 @@
+#******************************************************************************************
+#TODO:
+# x. someday. maybe. reimpl to browse via fcp.
+# x. page history is cleared if we get an error on loading a page. reimpl page history?
+# x. back-is-close like behaviour
+# x. backand forward buttons suck somehow. sometimes fwd is enabled even if no fwd is available. reimpl page history?
+# x. save page to disk
+# x. download. idea is to add dls to global download widget and mark them (some color code) as new content.
+# alt would be to to do it firefox like in a separate widget. maybe an option to adjust if browser dls should be
+# persistent or not
+# x. tool buttons do not adjust their size to icon size. maybe it is some global setting via qt-config
+# x. fProxy is a bit tight-lipped when it comes to feedback. no idea
+# x. give feedback on tabs about load / finisched / error. maybe some color code. wait for new QTabWidget features (qt4.5)
+# x. close button on tabs. wait for new QTabWidget features (qt4.5)
+# x. page actions: CopyImageToClipboard,
+# x. when mouse pointer is over an opend image a magnifier cursor appears. no idea how this is handled
+# x. open new tab on tab bar double click. IIRC looks like no way before qt4.5. tabBars are not stretched to fit in qt4.4
+# x. global feedback on statusbar flickers. reason: first label is holds arbitrary length text
+# x. fproxy. "force browser to dl" should we dl it in downloads or store emidiately? no idea
+# x. visiting plugins via fproxy does not work
+# x. real toolbars
+# x. remove host/port from urls?
+# x. browser settings - QWebSettings
+# x. shortcuts
+# x. user staring gui for first time. maybe we should not connext untill the user connects explicitely
+#******************************************************************************************
+"""
+
+@newfield signal: signal, signals
+"""
+from __future__ import absolute_import
+if __name__ == '__main__': # see --> http://bugs.python.org/issue1510172 . works only current dir and below
+ import os; __path__ = [os.path.dirname(__file__)]
+
+from PyQt4 import QtCore, QtGui, QtWebKit
+
+from . import config
+
+from .lib import fcp2
+from .lib.qt4ex.lib import tools as qtools
+from .lib.compactpath.qt4 import pathlabelwrap
+
+from . import Ui_DlgPropsBrowserObject
+from . import Ui_DlgDownloadKeyToDisk
+from .tpls.Ui_ViewBrowserWidgetTpl import Ui_ViewBrowserWidget
+#*****************************************************************************************
+#
+#*****************************************************************************************
+class Page(QtWebKit.QWebPage):
+ def __init__(self, parent):
+ QtWebKit.QWebPage.__init__(self, parent)
+
+ #def acceptNavigationRequest(self, frame, request, typeRequest):
+ # return True
+
+#*****************************************************************************************
+#
+#*****************************************************************************************
+class Browser(QtWebKit.QWebView):
+ """ browser customized for freenet
+ """
+
+ MaxProgress = 100
+
+ def __init__(self, parent=None, userData=None):
+ QtWebKit.QWebView.__init__(self, parent)
+
+ page = Page(self)
+ self.setPage(page)
+
+ #NOTE: we store last progress made to set busy cursor accordingly
+ self._lastProgress = 0
+ self._userData = userData
+
+ # connect actions
+ self.connect(self, QtCore.SIGNAL('loadStarted()'), self.onLoadStarted)
+ self.connect(self, QtCore.SIGNAL('loadProgress(int)'), self.onLoadProgress)
+ self.connect(self, QtCore.SIGNAL('loadFinished(bool)'), self.onLoadFinished)
+ self.connect(self.pageAction(QtWebKit.QWebPage.Stop), QtCore.SIGNAL('triggered()'), self.onActionStopTriggered)
+
+ ################################
+ ## methods
+ ################################
+ #def createWindow(self, typeWindow):
+ # pass
+
+ def load(self, url):
+ self._lastProgress = 0
+ return QtWebKit.QWebView.load(self, url)
+
+ def setLastStatusMessage(self, qString):
+ self._lastStatusMessage = qString
+
+ def setUrl(self, url):
+ return self.load(url)
+
+ def setContents(self, *args):
+ """sets the contents of the browser without changing its url"""
+ self._lastProgress = 0
+ return QtWebKit.QWebView.setContents(self, *args)
+
+ def setHtml(self, *args):
+ """sets the contents of the browser without changing its url"""
+ self._lastProgress = 0
+ return QtWebKit.QWebView.setHtm(self, *args)
+
+ def setPage(self, page):
+ """sets the contents of the browser without changing its url"""
+ self._lastProgress = 0
+ return QtWebKit.QWebView.setPage(self, page)
+
+ def setUserData(self, userData):
+ self._userData = userData
+
+ def mouseMoveEvent(self, event):
+ if self._lastProgress < self.MaxProgress:
+ self.setCursor(QtCore.Qt.BusyCursor)
+ else:
+ QtWebKit.QWebView.mouseMoveEvent(self, event)
+
+ def userData(self):
+ return self._userData
+
+ ###############################
+ ## event handlers
+ ###############################
+ def onActionStopTriggered(self):
+ # check wich cursor to set cos we may have busy cursor set
+ pt = self.mapFromGlobal(self.cursor().pos()) #TODO: self.mapFromGlobal(self.viewPort().cursor().pos()) ??
+ frame = self.page().currentFrame()
+ hitTest = frame.hitTestContent(pt)
+ #if not hitTest.isNull(): #TODO: looks like hitTest.isNull() alwas returns True
+ if hitTest.linkUrl().isValid():
+ self.setCursor(QtCore.Qt.PointingHandCursor)
+ else:
+ self.setCursor(QtCore.Qt.ArrowCursor)
+
+ def onLoadStarted(self):
+ self._lastProgress = 0
+
+ def onLoadProgress(self, n):
+ self._lastProgress = n
+
+ def onLoadFinished(self):
+ self._lastProgress = self.MaxProgress
+ self.onActionStopTriggered()
+
+ def onPageDownloadRequested(self, networkRequest):
+ self.emit(QtCore.SIGNAL('downloadRequested(const QNetworkRequest &)'), networkRequest)
+
+#**********************************************************************************
+#
+#**********************************************************************************
+class BrowserWidgetGlobalFeedback(config.GlobalFeedbackBase):
+ """wrapper for global statusbar widgets, menus"""
+
+ def __init__(self, parent, idGlobalFeedback):
+ config.GlobalFeedbackBase.__init__(self, parent, idGlobalFeedback)
+
+ # menus
+ self.menus = []
+ if self.menuBar is not None and hasattr(parent, 'fcViewObject'):
+ menu = QtGui.QMenu(parent.fcViewObject.displayName, self.menuBar)
+ parent.populateMenu(menu)
+ self.menus.append(menu)
+ self.menuBar.addViewMenu(menu)
+
+ # status bar widgets
+ self.labelStatus = None
+ self.progress = None
+ self.labelFeedbackWrap = None
+ if self.statusBar is not None:
+ self.labelStatus = QtGui.QLabel(QtCore.QString(), self.statusBar)
+ self.statusBar.addWidget(self.labelStatus)
+
+ self.progress = QtGui.QProgressBar(self.statusBar)
+ self.progress.setRange(0, Browser.MaxProgress)
+ self.progress.setValue(0)
+ self.statusBar.addWidget(self.progress)
+
+ label = QtGui.QLabel(self.statusBar)
+ label.setFrameStyle(QtGui.QLabel.Sunken | QtGui.QLabel.Box)
+ self.labelFeedbackWrap = pathlabelwrap.PathLabelWrap(
+ label,
+ path_module=config.CompactPathFcpKeyModule,
+ )
+ self.statusBar.addWidget(self.labelFeedbackWrap.label, 1)
+
+
+ def setVisible(self, flag):
+ if self.menuBar is not None:
+ for menu in self.menus:
+ menu.children()[0].setVisible(flag)
+ if self.statusBar is not None:
+ self.progress.setVisible(flag)
+ self.labelStatus.setVisible(flag)
+ self.labelFeedbackWrap.label.setVisible(flag)
+
+ def setProgress(self, n):
+ if self.progress is not None:
+ self.progress.setValue(n)
+
+ def setStatusMessage(self, qString):
+ if self.labelStatus is not None:
+ self.labelStatus.setText(qString)
+
+ def setFeedback(self, qString):
+ if self.labelFeedbackWrap is not None:
+ self.labelFeedbackWrap.setPath(unicode(qString))
+
+
+class BrowserWidgetViewObject(config.ViewObject):
+
+ def __init__(self, parent):
+ config.ViewObject. __init__(self, parent)
+
+ self.name=parent.objectName()
+ self.displayName=self.trUtf8('Browser')
+ self.icon=QtGui.QIcon()
+
+
+class BrowserWidgetSettings(config.SettingsBase):
+ _key_ = config.IdViewBrowserWidget
+ _settings_ = (
+ ('OpenLinksInNewTab', 'Bool', False, config.SettingScopeUser),
+ ('OpenAddressBarInNewTab', 'Bool', False, config.SettingScopeUser),
+ ('OpenBookmarksInNewTab', 'Bool', False, config.SettingScopeUser),
+ ('OpenHomePageOnNewTabCreated', 'Bool', False, config.SettingScopeUser),
+ ('BackIsClose', 'Bool', False, config.SettingScopeUser), #TODO: not implemented
+ ('HomePage', 'String', QtCore.QString(), config.SettingScopeUser),
+ ('IconSize', 'UInt', 32, config.SettingScopeUser),
+ ('IconTheme', 'String', QtCore.QString('crystal'), config.SettingScopeUser),
+ ('AutoLoadImages', 'Bool', True, config.SettingScopeUser), #TODO: not yet implemented
+ ('MaxTabText', 'UInt', 20, config.SettingScopeUser), #NOTE: make shure Max >= Min and Max and Min > 0
+ ('MinTabText', 'UInt', 7, config.SettingScopeUser),
+ )
+
+ def setValues(self, **kws):
+ autoLoadImages = kws.get('AutoLoadImages', None)
+ if autoLoadImages is not None:
+ browserWidget = self.parent()
+ tabWidget = browserWidget.controlById(browserWidget.IdTabBrowsers)
+ for i in xrange(tabWidget.count()):
+ browser = tabWidget.widget(i)
+ settings = browser.settings()
+ settings.setAttribute(settings.AutoLoadImages, autoLoadImages)
+ config.SettingsBase.setValues(self, **kws)
+
+ #backIsClose = kws.get('BackIsClose', None)
+ #if backIsClose is not None:
+ # self.parent()._adjustBackIsClose()
+
+
+
+class BrowserWidgetActions(config.ActionsBase):
+
+ def __init__(self, parent):
+ config.ActionsBase.__init__(self, parent)
+
+ iconSize = parent.fcSettings.value('IconSize')
+ iconTheme = parent.fcSettings.value('IconTheme')
+
+ self.action(
+ name='ActionCloseCurrentTab',
+ text=self.trUtf8('Close ¤t tab'),
+ trigger=parent.onCloseCurrentTab,
+ )
+ self.action( # context menu only
+ name='ActionCloseBrowserUnderMouse',
+ text=self.trUtf8('&Close tab'),
+ trigger=None,
+ )
+ self.action(
+ name='ActionCloseAllTabs',
+ text=self.trUtf8('Close &all tabs'),
+ trigger=parent.onCloseAllTabs,
+ )
+ self.action(
+ name='ActionOpenNewTab',
+ text=self.trUtf8('Open &new tab'),
+ trigger=parent.onOpenNewTab,
+ )
+ self.action(
+ name='ActionGoToFProxy',
+ text=self.trUtf8('Go to f&Proxy homepage'),
+ trigger=parent.onGoToFProxy,
+ )
+ self.action(
+ name='ActionGoToHomePage',
+ text=self.trUtf8('Go to &homepage'),
+ trigger=parent.onGoToHomePage,
+ )
+ self.action(
+ name='ActionObjectProperties',
+ text=self.trUtf8('Properties..'),
+ trigger=None,
+ )
+ self.action(
+ name='ActionZoomIn',
+ text=self.trUtf8('Zoom in'),
+ trigger=parent.onZoomIn,
+ )
+ self.action(
+ name='ActionZoomOut',
+ text=self.trUtf8('Zoom out'),
+ trigger=parent.onZoomOut,
+ )
+
+ # default browser actions
+ self.action(
+ name='ActionBack',
+ text=self.trUtf8('Back'),
+ trigger=None,
+ isEnabled=False,
+ icon=config.resources.getIcon('back', iconSize, iconTheme=iconTheme),
+ userData=(None, None),
+ )
+ self.action(
+ name='ActionForward',
+ text=self.trUtf8('Forward'),
+ trigger=None,
+ isEnabled=False,
+ icon=config.resources.getIcon('forward', iconSize, iconTheme=iconTheme),
+ userData=(None, None),
+ )
+ self.action(
+ name='ActionReload',
+ text=self.trUtf8('Reload'),
+ trigger=None,
+ isEnabled=False,
+ icon=config.resources.getIcon('reload_page', iconSize, iconTheme=iconTheme),
+ userData=(None, None),
+ )
+ self.action(
+ name='ActionStop',
+ text=self.trUtf8('Stop'),
+ trigger=None,
+ isEnabled=False,
+ icon=config.resources.getIcon('stop', iconSize, iconTheme=iconTheme),
+ userData=(None, None),
+ )
+
+ self.action(
+ name='ActionBackIsClose',
+ text=self.trUtf8('Back is close'),
+ icon=config.resources.getIcon('button_cancel', iconSize, iconTheme=iconTheme),
+ trigger=None,
+ )
+
+ # search actions
+ self.action(
+ parent=parent,
+ name='ActionSearch',
+ text=self.trUtf8('Search'),
+ shortcut=QtGui.QKeySequence(self.trUtf8('Ctrl+F')),
+ trigger=parent.onSearch,
+ )
+
+ def intertwineBrowserActions(self, browser=None):
+ """intertwines Browser actions with BrowserWidget actions
+ @note: call everytime the current browser changes
+ """
+ actions = (
+ ('ActionBack', QtWebKit.QWebPage.Back),
+ ('ActionForward', QtWebKit.QWebPage.Forward),
+ ('ActionReload', QtWebKit.QWebPage.Reload),
+ ('ActionStop', QtWebKit.QWebPage.Stop),
+ )
+ for actionName, pageAction in actions:
+ myPageAction = self[actionName]
+ newPageAction = None if browser is None else browser.pageAction(pageAction)
+ oldPageAction, cb = myPageAction.userData()
+
+ if oldPageAction is not None:
+ myPageAction.disconnect(oldPageAction, QtCore.SIGNAL('changed()'), cb)
+ oldPageAction.disconnect(myPageAction, QtCore.SIGNAL('triggered()'), oldPageAction.trigger)
+
+ if newPageAction is None:
+ myPageAction.setUserData((None, None))
+ myPageAction.setEnabled(False)
+ else:
+ def onActionChanged(browser=browser, myPageAction=myPageAction, browserPageAction=newPageAction):
+ myPageAction.setEnabled(browserPageAction.isEnabled())
+
+ myPageAction.setEnabled(newPageAction.isEnabled())
+ myPageAction.setUserData((newPageAction, onActionChanged))
+ myPageAction.connect(newPageAction, QtCore.SIGNAL('changed()'), onActionChanged)
+ newPageAction.connect(myPageAction, QtCore.SIGNAL('triggered()'), newPageAction.trigger)
+
+
+class LastBrowserState(object):
+ """records the last known state browser"""
+
+ __slots__ = ('icon', 'progress', 'statusMessage', 'title', 'url')
+
+ def __init__(self, icon=None, progress=0, statusMessage=None, title=None, url=None):
+ self.progress = 0
+ self.icon = tCore.QIcon() if icon is None else icon
+ self.statusMessage = QtCore.QString() if statusMessage is None else statusMessage
+ self.title = QtCore.QString() if title is None else title
+ #NOTE: opening a browser in a new tab may take a while to load.
+ # self.url() will return '' untill the page is found, so we handle
+ # it ourself and keep track of the last known url in self._lastUrl
+ # to give feedback to the user on the navbar. downside is we have
+ # to reimplement contextMenuEvent() :-(
+ self.url = QtCore.QUrl() if url is None else url
+
+#**********************************************************************************
+#
+#**********************************************************************************
+#TODO: strip host:port on address bar?
+#TODO: rename home page to start page
+class ViewBrowserWidget(QtGui.QWidget, Ui_ViewBrowserWidget):
+
+ IdTabBrowsers = 'tabBrowsers'
+ IdFrameTools = 'frameTools'
+ IdFrameAddressBar = 'frameAddressBar'
+ IdEdAddressBar = 'edAddressBar'
+
+ IdBtBack = 'btBack'
+ IdBtForward = 'btForward'
+ IdBtReload = 'btReload'
+ IdBtStop = 'btStop'
+
+ IdFrameSearch = 'frameSearch'
+ IdEdSearch = 'edSearch'
+ IdBtSearchUpwards = 'btSearchUpwards'
+ IdBtSearchDownwards = 'btSearchDownwards'
+ IdCkSearchCaseSensitive = 'ckSearchCaseSensitive'
+
+ ForcedMinBrowserTabText = 5 # forced minimum number of chars on browser tabBar
+
+ def __init__(self, parent, idGlobalFeedback=config.IdMainWindow):
+ QtGui.QWidget.__init__(self, parent)
+
+ self.setupUi(self)
+ config.ObjectRegistry.register(self)
+
+ self._initialConfigDataArrived = False
+
+ self.fcSettings = BrowserWidgetSettings(self).restore()
+ self.fcActions = BrowserWidgetActions(self)
+ self.fcViewObject = BrowserWidgetViewObject(self)
+ self.fcGlobalFeedback = BrowserWidgetGlobalFeedback(self, idGlobalFeedback)
+
+ # setup tab bar
+ tabWidget = self.controlById(self.IdTabBrowsers)
+ tabWidget.clear()
+ tabWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
+ self.connect(tabWidget, QtCore.SIGNAL('currentChanged(int)'), self.onTabCurrentChanged)
+ self.connect(tabWidget, QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'), self.onTabContextMenuEvent)
+
+ # setup addressbar
+ addressbar = self.controlById(self.IdEdAddressBar)
+ self.connect(addressbar, QtCore.SIGNAL('returnPressed()'), self.onNavBarReturnPressed)
+
+ # setup tool buttons
+ self.controlById(self.IdBtBack).setDefaultAction(self.fcActions['ActionBack'])
+ self.controlById(self.IdBtForward).setDefaultAction(self.fcActions['ActionForward'])
+ self.controlById(self.IdBtReload).setDefaultAction(self.fcActions['ActionReload'])
+ self.controlById(self.IdBtStop).setDefaultAction(self.fcActions['ActionStop'])
+
+ # setupp search bar
+ bt = self.controlById(self.IdBtSearchUpwards)
+ self.connect(bt, QtCore.SIGNAL('clicked()'), self.onSearchUpwards)
+ bt = self.controlById(self.IdBtSearchDownwards)
+ self.connect(bt, QtCore.SIGNAL('clicked()'), self.onSearchDownwards)
+ ed = self.controlById(self.IdEdSearch)
+ self.connect(ed, QtCore.SIGNAL('returnPressed()'), self.onSearchDownwards)
+ frameSearch = self.controlById(self.IdFrameSearch)
+ frameSearch.setVisible(False)
+
+ # fire up a new broser to make a start
+ self.newBrowser(title=self.trUtf8('Waiting for fproxy'))
+ self.fcActions['ActionGoToHomePage'].trigger()
+
+ #########################################
+ ## private methods
+ #########################################
+ #NOTE: to reduce flicker set min size to max size
+ def _adjustTabText(self, qString):
+ maxTabText = self.fcSettings.value('MaxTabText')
+ minTabText = self.fcSettings.value('MinTabText')
+ ellipsis = self.trUtf8('..')
+
+ if minTabText < self.ForcedMinBrowserTabText:
+ minTabText = self.ForcedMinBrowserTabText
+ self.fcSettings.setValues(MinTabText=minTabText)
+ if maxTabText < self.ForcedMinBrowserTabText:
+ maxTabText = self.ForcedMinBrowserTabText
+ self.fcSettings.setValues(MaxTabText=maxTabText)
+ if minTabText > maxTabText:
+ minTabText = maxTabText
+ self.fcSettings.setValues(MinTabText=maxTabText)
+
+ if qString.count() < minTabText:
+ qString = qString.append('\x20' * (minTabText - qString.count()))
+ else:
+ if maxTabText < self.ForcedMinBrowserTabText:
+ maxTabText = sminTabText
+ qString = qtools.truncateString(maxTabText, qString, ellipsis)
+ return qString
+
+ def _downloadImageToDisk(self, hitTestResult):
+ px = hitTestResult.pixmap()
+ if px.isNull():
+ return False
+
+ key = config.qStringToFcpKey(hitTestResult.imageUrl().toString())
+ if key is None:
+ return False
+
+ # thow a dialog box at the user to select a filename
+ # ..qt seems to place the filename part as suggestion into the filename box. so try it
+ caption = config.FclientAppName + self.trUtf8(' - Save Image To..')
+ directory = unicode(config.settings.value('DownloadDir'))
+ fileName = unicode(config.guessFileNameFromKey(key, default=QtCore.QString('')))
+
+ if directory and fileName:
+ directory = os.path.join(directory, fileName)
+ elif not directory:
+ directory = fileName
+ filePath = QtGui.QFileDialog.getSaveFileName(self, caption, directory)
+
+ if filePath:
+ filePath= unicode(filePath)
+ if os.path.exists(filePath):
+ try:
+ os.remove(filePath)
+ except Exception, details:
+ QtGui.QMessageBox.critical(
+ self,
+ caption,
+ self.trUtf8('Could not remove file'), #NOTE: no details please, may contain arbitrary lenght filepath
+ )
+ return False
+ px.save(filePath)
+ return True
+
+ def _downloadKeyToDisk(self, qUrl):
+ """
+ @return: (bool) False if the key in the url is invalid, True otherwise
+ """
+ fcpKey = config.qStringToFcpKe...
[truncated message content] |