Example #1
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if dex.isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     if not event.buttons() & Qt.LeftButton:
         return
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize())
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if self._model.is_in_user_category(dex):
         drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Example #2
0
 def __init__(self, parent, url=''):
     super(WebView, self).__init__(parent)
     self.draging = False
     self.drag = QDrag(self)
     self.dragStartPos = None
     self.webPage = WebPage()
     self.setPage(self.webPage)
     self.mainFrame = self.page().mainFrame()
     self.setAttribute(Qt.WA_DeleteOnClose, True)
     self.titleChanged.connect(parent.setWindowTitle)
     self.load(url)
     webSettings = self.settings()
     webSettings.setDefaultTextEncoding("utf-8")
     # webSettings.setOfflineStorageDefaultQuota(sys.maxsize)
     # webSettings.setOfflineWebApplicationCacheQuota(sys.maxsize)
     webSettings.enablePersistentStorage(assets.fs.dataPath())
     webSettings.setAttribute(QWebSettings.PluginsEnabled, True)
     webSettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
     webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
     webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True)
     webSettings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True)
     webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
     webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
     webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
     webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard,
                              True)
     webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls,
                              True)
     webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls,
                              True)
     self.mainFrame.javaScriptWindowObjectCleared.connect(
         self.setJavaScriptObject)
     self.mainFrame.iconChanged.connect(self.changeIcon)
Example #3
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if dex.isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     if not event.buttons() & Qt.LeftButton:
         return
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize())
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if self._model.is_in_user_category(dex):
         drag.exec_(Qt.CopyAction|Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Example #4
0
    def mouseMoveEvent(self, event):
        '''
        @param: event QMouseEvent
        '''
        if not self._locationBar or event.buttons() != Qt.LeftButton:
            super().mouseMoveEvent(event)
            return

        manhattanLength = (event.pos() -
                           self._drawStartPosition).manhattanLength()
        if manhattanLength <= QApplication.startDragDistance():
            super().mouseMoveEvent(event)
            return

        url = self._locationBar.webView().url()
        title = self._locationBar.webView().title()

        if url.isEmpty() or not title:
            super().mouseMoveEvent(event)
            return

        drag = QDrag(self)
        mime = QMimeData()
        mime.setUrls([url])
        mime.setText(title)
        mime.setImageData(self.icon.pixmap(16).toImage())

        drag.setMimeData(mime)
        drag.setPixmap(
            gVar.appTools.createPixmapForSite(self.icon, title,
                                              url.toString()))
        drag.exec_()

        # Restore Down State
        self.setDown(False)
Example #5
0
	def __init__(self, parent, url = ''):
		super(WebView, self).__init__(parent)
		self.draging = False
		self.drag = QDrag(self)
		self.webPage = WebPage()
		self.setPage(self.webPage)
		self.mainFrame = self.page().mainFrame()
		self.setAttribute(Qt.WA_DeleteOnClose, True)
		self.titleChanged.connect(parent.setWindowTitle)
		self.load(url)
		webSettings = self.settings()
		webSettings.setDefaultTextEncoding("utf-8")
		# webSettings.setOfflineStorageDefaultQuota(sys.maxsize)
		# webSettings.setOfflineWebApplicationCacheQuota(sys.maxsize)
		webSettings.enablePersistentStorage(assets.fs.dataPath())
		webSettings.setAttribute(QWebSettings.PluginsEnabled, True)
		webSettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
		webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
		webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True)
		webSettings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True)
		webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
		webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True)
		webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
		self.mainFrame.javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
		self.mainFrame.iconChanged.connect(self.changeIcon)
Example #6
0
 def mouseMoveEvent(self, event):
     if not (event.buttons() & Qt.LeftButton):
         return
     if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
         return
     drag = QDrag(self)
     
     mimedata = QMimeData()
     mimedata.setParent(self)
     mimedata.setText(self.text())
     drag.setMimeData(mimedata)
     pixmap = QPixmap(self.size())
     painter = QPainter(pixmap)
     painter.drawPixmap(self.rect(), self.grab())
     painter.end()
     drag.setPixmap(pixmap)
     drag.setHotSpot(event.pos())
     drag.exec_(Qt.CopyAction | Qt.MoveAction)
Example #7
0
 def mousePressEvent(self, ev):
     if ev.button() == QtCore.Qt.LeftButton:
         drag = QDrag(self)
         mimeData = QMimeData()
         mimeData.setText(self.content)
         drag.setMimeData(mimeData)
         drag.setPixmap(iconPixmap)
         dropAction = drag.exec()
Example #8
0
 def mouseMoveEvent(self, event):
     dex = self.indexAt(event.pos())
     if dex.isValid():
         self.setCursor(Qt.PointingHandCursor)
     else:
         self.unsetCursor()
     if not event.buttons() & Qt.LeftButton:
         return
     if self.in_drag_drop or not dex.isValid():
         QTreeView.mouseMoveEvent(self, event)
         return
     # don't start drag/drop until the mouse has moved a bit.
     if ((event.pos() - self.possible_drag_start).manhattanLength() <
                                 QApplication.startDragDistance()):
         QTreeView.mouseMoveEvent(self, event)
         return
     # Must deal with odd case where the node being dragged is 'virtual',
     # created to form a hierarchy. We can't really drag this node, but in
     # addition we can't allow drag recognition to notice going over some
     # other node and grabbing that one. So we set in_drag_drop to prevent
     # this from happening, turning it off when the user lifts the button.
     self.in_drag_drop = True
     if not self._model.flags(dex) & Qt.ItemIsDragEnabled:
         QTreeView.mouseMoveEvent(self, event)
         return
     md = self._model.mimeData([dex])
     pixmap = dex.data(DRAG_IMAGE_ROLE).pixmap(self.iconSize())
     drag = QDrag(self)
     drag.setPixmap(pixmap)
     drag.setMimeData(md)
     if (self._model.is_in_user_category(dex) or
                 self._model.is_index_on_a_hierarchical_category(dex)):
         '''
         Things break if we specify MoveAction as the default, which is
         what we want for drag on hierarchical categories. Dragging user
         categories stops working. Don't know why. To avoid the problem
         we fix the action in dragMoveEvent.
         '''
         drag.exec_(Qt.CopyAction|Qt.MoveAction, Qt.CopyAction)
     else:
         drag.exec_(Qt.CopyAction)
Example #9
0
 def drag_data(self):
     m = self.model()
     rows = self.selectionModel().selectedRows()
     paths = [force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows) if p]
     md = QMimeData()
     md.setData('application/calibre+from_device', 'dummy')
     md.setUrls([QUrl.fromLocalFile(p) for p in paths])
     drag = QDrag(self)
     drag.setMimeData(md)
     cover = self.drag_icon(m.cover(self.currentIndex().row()), len(paths) >
             1)
     drag.setHotSpot(QPoint(-15, -15))
     drag.setPixmap(cover)
     return drag
Example #10
0
 def __init__(self, parent, url = ''):
     super(WebView, self).__init__(parent)
     self.draging = False
     self.assets = assets
     self.window = parent
     self.drag = QDrag(self)
     self.dragStartPos = None
     self.webPage = WebPage()
     if not assets.manifest['debug']:
         actions = [
                 "OpenLink",
                 "OpenLinkInNewWindow",
                 "OpenLinkInThisWindow",
                 "OpenFrameInNewWindow",
                 "DownloadLinkToDisk",
                 "CopyLinkToClipboard",
                 "OpenImageInNewWindow",
                 "DownloadImageToDisk",
                 "CopyImageToClipboard",
                 "CopyImageUrlToClipboard",
                 "Back",
                 "Forward",
                 "Reload",
                 "ReloadAndBypassCache",
                 ]
         for action in actions:
             action_id = getattr(QWebPage, action)
             q_action = self.webPage.action(action_id)
             if q_action:
                 q_action.setVisible(False)
     self.setPage(self.webPage)
     self.mainFrame = self.page().mainFrame()
     self.setAttribute(Qt.WA_DeleteOnClose, True)
     self.titleChanged.connect(self.window.setWindowTitle)
     webSettings = self.settings()
     webSettings.setDefaultTextEncoding("utf-8")
     webSettings.enablePersistentStorage(assets.fs.dataPath())
     webSettings.setAttribute(QWebSettings.PluginsEnabled, True)
     webSettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
     webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
     webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True)
     webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, assets.manifest['debug'])
     webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
     webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
     webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
     webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True)
     webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
     self.mainFrame.javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
     self.mainFrame.iconChanged.connect(self.changeIcon)
     self.load(url)
Example #11
0
 def drag_data(self):
     m = self.model()
     rows = self.selectionModel().selectedRows()
     paths = [force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows) if p]
     md = QMimeData()
     md.setData("application/calibre+from_device", b"dummy")
     md.setUrls([QUrl.fromLocalFile(p) for p in paths])
     drag = QDrag(self)
     drag.setMimeData(md)
     cover = self.drag_icon(m.cover(self.currentIndex().row()), len(paths) > 1)
     drag.setHotSpot(QPoint(-15, -15))
     drag.setPixmap(cover)
     return drag
    def mouseMoveEvent(self, event):
        '''
        @param: event QMouseEvent
        '''
        if (event.pos() - self._dragStartPosition
            ).manhattanLength() < QApplication.startDragDistance():
            super().mouseMoveEvent(event)
            return

        self.setDown(False)

        drag = QDrag(self)
        mime = BookmarksButtonMimeData()
        mime.setBookmarkItem(self._bookmark)
        drag.setMimeData(mime)
        drag.setPixmap(self.grab())
        drag.exec_()
Example #13
0
def drag_data(self):
    m = self.model()
    db = m.db
    selected = self.get_selected_ids()
    ids = ' '.join(map(str, selected))
    md = QMimeData()
    md.setData('application/calibre+from_library', ids.encode('utf-8'))
    fmt = prefs['output_format']

    def url_for_id(i):
        try:
            ans = db.format_path(i, fmt, index_is_id=True)
        except:
            ans = None
        if ans is None:
            fmts = db.formats(i, index_is_id=True)
            if fmts:
                fmts = fmts.split(',')
            else:
                fmts = []
            for f in fmts:
                try:
                    ans = db.format_path(i, f, index_is_id=True)
                except:
                    ans = None
        if ans is None:
            ans = db.abspath(i, index_is_id=True)
        return QUrl.fromLocalFile(ans)

    md.setUrls([url_for_id(i) for i in selected])
    drag = QDrag(self)
    col = self.selectionModel().currentIndex().column()
    try:
        md.column_name = self.column_map[col]
    except AttributeError:
        md.column_name = 'title'
    drag.setMimeData(md)
    cover = self.drag_icon(m.cover(self.currentIndex().row()),
            len(selected) > 1)
    drag.setHotSpot(QPoint(-15, -15))
    drag.setPixmap(cover)
    return drag
Example #14
0
def drag_data(self):
    m = self.model()
    db = m.db
    selected = self.get_selected_ids()
    ids = ' '.join(map(str, selected))
    md = QMimeData()
    md.setData('application/calibre+from_library', ids.encode('utf-8'))
    fmt = prefs['output_format']

    def url_for_id(i):
        try:
            ans = db.format_path(i, fmt, index_is_id=True)
        except:
            ans = None
        if ans is None:
            fmts = db.formats(i, index_is_id=True)
            if fmts:
                fmts = fmts.split(',')
            else:
                fmts = []
            for f in fmts:
                try:
                    ans = db.format_path(i, f, index_is_id=True)
                except:
                    ans = None
        if ans is None:
            ans = db.abspath(i, index_is_id=True)
        return QUrl.fromLocalFile(ans)

    md.setUrls([url_for_id(i) for i in selected])
    drag = QDrag(self)
    col = self.selectionModel().currentIndex().column()
    try:
        md.column_name = self.column_map[col]
    except AttributeError:
        md.column_name = 'title'
    drag.setMimeData(md)
    cover = self.drag_icon(m.cover(self.currentIndex().row()),
            len(selected) > 1)
    drag.setHotSpot(QPoint(-15, -15))
    drag.setPixmap(cover)
    return drag
    def mouseMoveEvent(self, event):
        '''
        @param: event QMouseEvent
        '''
        if not (event.buttons() & Qt.LeftButton) or len(
                self.selectedText()) != len(self.text()):
            super().mouseMoveEvent(event)
            return

        manhattanLength = (event.pos() - self._dragStart).manhattanLength()
        if manhattanLength <= QApplication.startDragDistance():
            return

        drag = QDrag(self)
        mime = QMimeData()
        mime.setText(self._originalText)

        drag.setMimeData(mime)
        drag.exec_()
Example #16
0
    def mouseMoveEvent(self, event):
        '''
        @param: event QMouseEvent
        '''
        super().mouseMoveEvent(event)

        if gVar.app.plugins().processMouseMove(const.ON_TabBar, self, event):
            return

        if self.count() == 1 and gVar.app.windowCount() == 1:
            return

        if not self._dragStartPosition.isNull():
            offset = 0
            eventY = event.pos().y()
            if eventY < 0:
                offset = abs(eventY)
            elif eventY > self.height():
                offset = eventY - self.height()
            if offset > QApplication.startDragDistance() * 3:
                global_ = self.mapToGlobal(self._dragStartPosition)
                w = QApplication.widgetAt(global_)
                if w:
                    mouse = QMouseEvent(QEvent.MouseButtonRelease,
                                        w.mapFromGlobal(global_),
                                        Qt.LeftButton, Qt.LeftButton,
                                        event.modifiers())
                    QApplication.sendEvent(w, mouse)
                drag = QDrag(self)
                mime = QMimeData()
                mime.setData(self.MIMETYPE, b'')
                drag.setMimeData(mime)
                drag.setPixmap(self.tabPixmap(self.currentIndex()))
                if drag.exec_() == Qt.IgnoreAction:
                    self._tabWidget.detachTabByIndex(self.currentIndex())
                return
Example #17
0
class WebView(QWebView):
    def __init__(self, parent, url=''):
        super(WebView, self).__init__(parent)
        self.draging = False
        self.drag = QDrag(self)
        self.dragStartPos = None
        self.webPage = WebPage()
        self.setPage(self.webPage)
        self.mainFrame = self.page().mainFrame()
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.titleChanged.connect(parent.setWindowTitle)
        self.load(url)
        webSettings = self.settings()
        webSettings.setDefaultTextEncoding("utf-8")
        # webSettings.setOfflineStorageDefaultQuota(sys.maxsize)
        # webSettings.setOfflineWebApplicationCacheQuota(sys.maxsize)
        webSettings.enablePersistentStorage(assets.fs.dataPath())
        webSettings.setAttribute(QWebSettings.PluginsEnabled, True)
        webSettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
        webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True)
        webSettings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True)
        webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
        webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
        webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
        webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard,
                                 True)
        webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls,
                                 True)
        webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls,
                                 True)
        self.mainFrame.javaScriptWindowObjectCleared.connect(
            self.setJavaScriptObject)
        self.mainFrame.iconChanged.connect(self.changeIcon)

    def load(self, url=''):
        p = re.compile('(^file:\/\/)|(^http:\/\/)|(^https:\/\/)|(^data:)')
        if url and p.match(url) == None:
            url = QUrl.fromLocalFile(os.path.abspath(url))
        else:
            url = QUrl(url)
        super(WebView, self).load(url)

    def eval(self, javaScript):
        return self.mainFrame.evaluateJavaScript(javaScript)

    def changeIcon(self):
        self.parentWidget().setWindowIcon(self.mainFrame.icon())
        # self.parentWidget().setWindowIcon(QWebSettings.iconForUrl(self.url()))

    def setJavaScriptObject(self):
        self.mainFrame.addToJavaScriptWindowObject('HAE',
                                                   self.parentWidget().api)
        self.mainFrame.addToJavaScriptWindowObject('HAE_app',
                                                   self.parentWidget())
        self.mainFrame.addToJavaScriptWindowObject('HAE_fs', assets.fs)
        self.mainFrame.addToJavaScriptWindowObject('HAE_sys', assets.sys)
        self.mainFrame.addToJavaScriptWindowObject('HAE_codec', assets.codec)
        self.eval('''
			(function(){
				initModule('fs');
				initModule('sys');
				initModule('app');
				initModule('codec');
				initClass('Window');
				initClass('Dialog');
				initClass('FileDialog');
				initClass('File');
				initClass('Menu');
				initClass('MenuItem');
				initClass('TrayIcon');
				initClass('Downloader');
				initClass('Process');
				initClass('SocketServer');
				initClass('SocketClient');
				function initClass(name){
					HAE[name] = function(){
						return initEventBinder(HAE['create' + name].apply(window, arguments));
					};
				}
				function initModule(name){
					var key = 'HAE_' + name;
					HAE[name] = initEventBinder(window[key]);
					delete window[key];
				}
				function initEventBinder(object){
					object.addEvent = function(event, handler){
						if(typeof event == 'string'){
							var eventName = event;
							event = ('on' + event).toLowerCase();
							if(event in this && this[event].connect){
								this[event].connect(handler);
							}else{
								console.warn('Warning: This object dose not have "' + eventName + '" event');
							}
						}else if(typeof event == 'object'){
							for(var key in event){
								this.addEvent(key, event[key]);
							}
						}
					};
					object.removeEvent = function(event, handler){
						event = 'on' + event;
						console.log(this[event]);
						if(event in this && this[event].connect){
							this[event].disconnect(handler);
						}
					};
					return object;
				}
			})();
		''')

    def mousePressEvent(self, event):
        self.parentWidget().mousePressEvent(event)
        if not self.parentWidget().isDraging():
            super(WebView, self).mousePressEvent(event)
            if event.buttons() == Qt.LeftButton:
                mimeData = QMimeData()
                hitTestResult = self.mainFrame.hitTestContent(event.pos())
                # print(hitTestResult.linkUrl())
                # dragging the scrollbar
                if hitTestResult.isNull():
                    self.draging = True
                if hitTestResult.isContentSelected():
                    mimeData.setText(self.selectedText())
                    mimeData.setHtml(self.selectedHtml())
                elif not hitTestResult.linkUrl().isEmpty():
                    mimeData.setUrls([hitTestResult.linkUrl()])
                    mimeData.setHtml(hitTestResult.element().toOuterXml())
                elif not hitTestResult.pixmap().isNull():
                    mimeData.setImageData(hitTestResult.pixmap())
                    mimeData.setUrls([hitTestResult.imageUrl()])
                    mimeData.setHtml(hitTestResult.element().toOuterXml())
                    # mimeData.setData('application/x-qt-windows-mime;value="FileContents"', QVariant(hitTestResult.pixmap()).toByteArray())
                # elif not hitTestResult.mediaUrl().isEmpty():
                # 	mimeData.setUrls([hitTestResult.mediaUrl()])
                # 	mimeData.setHtml(hitTestResult.element().toOuterXml())
                else:
                    return
                # pixmap = hitTestResult.pixmap()
                # pixmap.setMask(QBitmap.fromImage(pixmap.toImage()))
                self.drag.setMimeData(mimeData)
                self.dragStartPos = event.pos()
                # self.drag.setPixmap(pixmap)
                # self.drag.setHotSpot(QPoint(self.drag.pixmap().width() / 2, self.drag.pixmap().height() / 2))

    def mouseMoveEvent(self, event):
        if not self.parentWidget().isDraging():
            super(WebView, self).mouseMoveEvent(event)
            if self.dragStartPos and (
                    event.pos() - self.dragStartPos
            ).manhattanLength() >= QApplication.startDragDistance():
                self.drag.exec()
                self.dragStartPos = None
                self.drag.setMimeData(None)
        if not self.draging:
            event.ignore()

    def mouseReleaseEvent(self, event):
        self.draging = False
        super(WebView, self).mouseReleaseEvent(event)
        self.dragStartPos = None
        self.drag.setMimeData(None)
        event.ignore()

    def close(self):
        self.stop()
        self.load()
        self.page().close()
        self.eval('HAE = null')
        self.drag.setMimeData(None)
        super(WebView, self).close()
Example #18
0
class WebView(QWebView):
	def __init__(self, parent, url = ''):
		super(WebView, self).__init__(parent)
		self.draging = False
		self.drag = QDrag(self)
		self.webPage = WebPage()
		self.setPage(self.webPage)
		self.mainFrame = self.page().mainFrame()
		self.setAttribute(Qt.WA_DeleteOnClose, True)
		self.titleChanged.connect(parent.setWindowTitle)
		self.load(url)
		webSettings = self.settings()
		webSettings.setDefaultTextEncoding("utf-8")
		# webSettings.setOfflineStorageDefaultQuota(sys.maxsize)
		# webSettings.setOfflineWebApplicationCacheQuota(sys.maxsize)
		webSettings.enablePersistentStorage(assets.fs.dataPath())
		webSettings.setAttribute(QWebSettings.PluginsEnabled, True)
		webSettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
		webSettings.setAttribute(QWebSettings.XSSAuditingEnabled, True)
		webSettings.setAttribute(QWebSettings.CSSGridLayoutEnabled, True)
		webSettings.setAttribute(QWebSettings.ScrollAnimatorEnabled, True)
		webSettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanCloseWindows, True)
		webSettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True)
		webSettings.setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True)
		webSettings.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
		self.mainFrame.javaScriptWindowObjectCleared.connect(self.setJavaScriptObject)
		self.mainFrame.iconChanged.connect(self.changeIcon)

	def load(self, url = ''):
		p = re.compile('(^file:\/\/)|(^http:\/\/)|(^https:\/\/)|(^data:)')
		if url and p.match(url) == None:
			url = QUrl.fromLocalFile(os.path.abspath(url))
		else:
			url = QUrl(url)
		super(WebView, self).load(url)

	def eval(self, javaScript):
		return self.mainFrame.evaluateJavaScript(javaScript)

	def changeIcon(self):
		self.parentWidget().setWindowIcon(self.mainFrame.icon())
		# self.parentWidget().setWindowIcon(QWebSettings.iconForUrl(self.url()))

	def setJavaScriptObject(self):
		self.mainFrame.addToJavaScriptWindowObject('HAE', self.parentWidget().api)
		self.mainFrame.addToJavaScriptWindowObject('HAE_app', self.parentWidget())
		self.mainFrame.addToJavaScriptWindowObject('HAE_fs', assets.fs)
		self.mainFrame.addToJavaScriptWindowObject('HAE_sys', assets.sys)
		self.mainFrame.addToJavaScriptWindowObject('HAE_codec', assets.codec)
		self.eval('''
			(function(){
				initModule('fs');
				initModule('sys');
				initModule('app');
				initModule('codec');
				initClass('Window');
				initClass('Dialog');
				initClass('FileDialog');
				initClass('File');
				initClass('Menu');
				initClass('MenuItem');
				initClass('TrayIcon');
				initClass('Downloader');
				initClass('Process');
				initClass('SocketServer');
				initClass('SocketClient');
				function initClass(name){
					HAE[name] = function(){
						return initEventBinder(HAE['create' + name].apply(window, arguments));
					};
				}
				function initModule(name){
					var key = 'HAE_' + name;
					HAE[name] = initEventBinder(window[key]);
					delete window[key];
				}
				function initEventBinder(object){
					object.addEvent = function(event, handler){
						if(typeof event == 'string'){
							var eventName = event;
							event = ('on' + event).toLowerCase();
							if(event in this && this[event].connect){
								this[event].connect(handler);
							}else{
								console.warn('Warning: This object dose not have "' + eventName + '" event');
							}
						}else if(typeof event == 'object'){
							for(var key in event){
								this.addEvent(key, event[key]);
							}
						}
					};
					object.removeEvent = function(event, handler){
						event = 'on' + event;
						console.log(this[event]);
						if(event in this && this[event].connect){
							this[event].disconnect(handler);
						}
					};
					return object;
				}
			})();
		''')

	def mousePressEvent(self, event):
		self.parentWidget().mousePressEvent(event)
		if not self.parentWidget().isDraging():
			super(WebView, self).mousePressEvent(event)
			if event.buttons() == Qt.LeftButton:
				mimeData = QMimeData()
				hitTestResult = self.mainFrame.hitTestContent(event.pos())
				# print(hitTestResult.linkUrl())
				# dragging the scrollbar
				if hitTestResult.isNull():
					self.draging = True
				if hitTestResult.isContentSelected():
					mimeData.setText(self.selectedText())
					mimeData.setHtml(self.selectedHtml())
				elif not hitTestResult.linkUrl().isEmpty():
					mimeData.setUrls([hitTestResult.linkUrl()])
					mimeData.setHtml(hitTestResult.element().toOuterXml())
				elif not hitTestResult.pixmap().isNull():
					mimeData.setImageData(hitTestResult.pixmap())
					mimeData.setUrls([hitTestResult.imageUrl()])
					mimeData.setHtml(hitTestResult.element().toOuterXml())
					# mimeData.setData('application/x-qt-windows-mime;value="FileContents"', QVariant(hitTestResult.pixmap()).toByteArray())
				# elif not hitTestResult.mediaUrl().isEmpty():
				# 	mimeData.setUrls([hitTestResult.mediaUrl()])
				# 	mimeData.setHtml(hitTestResult.element().toOuterXml())
				else:
					return
				# pixmap = hitTestResult.pixmap()
				# pixmap.setMask(QBitmap.fromImage(pixmap.toImage()))
				self.drag.setMimeData(mimeData)
				# self.drag.setPixmap(pixmap)
				# self.drag.setHotSpot(QPoint(self.drag.pixmap().width() / 2, self.drag.pixmap().height() / 2))

	def mouseMoveEvent(self, event):
		if not self.parentWidget().isDraging():
			super(WebView, self).mouseMoveEvent(event)
			if self.drag.mimeData():
				self.drag.exec()
				self.drag.setMimeData(None)
		if not self.draging:
			event.ignore()

	def mouseReleaseEvent(self, event):
		self.draging = False
		super(WebView, self).mouseReleaseEvent(event)
		self.drag.setMimeData(None)
		event.ignore()

	def close(self):
		self.stop()
		self.load()
		self.page().close()
		self.eval('HAE = null')
		self.drag.setMimeData(None)
		super(WebView, self).close()