Skip to content

Commit

Permalink
Slight restructuring to enable better docs
Browse files Browse the repository at this point in the history
- All widget classes are now in separate files in the widgets/ folder
instead of all in a single widgets.py file.
- Moved check_if_os_file and QElidedLabel to util module
- Updated doc gen files
  • Loading branch information
dschreij committed May 12, 2016
1 parent db7b1d1 commit 657be6e
Show file tree
Hide file tree
Showing 10 changed files with 996 additions and 785 deletions.
3 changes: 2 additions & 1 deletion QOpenScienceFramework/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
dirname = safe_decode(os.path.dirname(__file__),
enc=sys.getfilesystemencoding())

import QOpenScienceFramework.widgets
import QOpenScienceFramework.connection
import QOpenScienceFramework.manager
import QOpenScienceFramework.widgets

9 changes: 5 additions & 4 deletions QOpenScienceFramework/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
import uuid

# OSF modules
from QOpenScienceFramework import events, loginwindow
from QOpenScienceFramework import events
from QOpenScienceFramework.widgets import LoginWindow
# Python 2 and 3 compatiblity settings
from QOpenScienceFramework.compat import *

Expand Down Expand Up @@ -107,7 +108,7 @@ def __init__(self, *args, **kwargs):
self.warning_message.connect(self.notifier.warning)

# Init browser in which login page is displayed
self.browser = loginwindow.LoginWindow()
self.browser = LoginWindow()
self.browser.setWindowTitle(_(u"Log in to OSF"))
# Make sure browser closes if parent QWidget closes
if isinstance(self.parent(), QtWidgets.QWidget):
Expand Down Expand Up @@ -719,8 +720,8 @@ def upload_file(self, url, source_file, *args, **kwargs):
----------
url : string / QtCore.QUrl
The target url that points to endpoint handling the upload
source : string / QtCore.QtFile
The path and file which should be uploaded.
source_file : string / QtCore.QtFile
The path to the file which should be uploaded.
finishedCallback : function (default: None)
The function to call once the upload is finished.
uploadProgress : function (default: None)
Expand Down
43 changes: 43 additions & 0 deletions QOpenScienceFramework/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
"""
Utility functions and classes used throughout the module
"""

import os
from qtpy import QtWidgets, QtGui, QtCore

def check_if_opensesame_file(filename, os3_only=False):
""" Checks if the passed file is an OpenSesame file, based on its extension.
Parameters
----------
filename : string
The file to check
os3_only : bool (default: False)
Only check for the newer .osexp files (from OpenSesasme 3 on), if this
parameter is set to True, this function will return False for legacy
.opensesame and .opensesame.tar.gz formats
Returns
-------
boolean :
True if filename is an OpenSesame file, False if not
"""
ext = os.path.splitext(filename)[1]
if os3_only:
return ext == '.osexp'

if ext in ['.osexp', '.opensesame'] or \
(ext == '.gz' and 'opensesame.tar.gz' in filename):
return True
return False

class QElidedLabel(QtWidgets.QLabel):
""" Label that elides its contents by overwriting paintEvent"""
def paintEvent(self, event):
painter = QtGui.QPainter(self)
metrics = QtGui.QFontMetrics(self.font())
elided = metrics.elidedText(self.text(), QtCore.Qt.ElideRight, self.width())
painter.drawText(self.rect(), self.alignment(), elided)

__all__ = ['check_if_opensesame_file', 'QElidedLabel']
6 changes: 6 additions & 0 deletions QOpenScienceFramework/widgets/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from QOpenScienceFramework.widgets.loginwindow import LoginWindow
from QOpenScienceFramework.widgets.userbadge import UserBadge
from QOpenScienceFramework.widgets.osfexplorer import OSFExplorer
from QOpenScienceFramework.widgets.projecttree import ProjectTree

__all__ = ['LoginWindow', 'UserBadge', 'OSFExplorer', 'ProjectTree']
120 changes: 120 additions & 0 deletions QOpenScienceFramework/widgets/loginwindow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-

# Python3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import logging
logging.basicConfig(level=logging.INFO)

# QT classes
# Required QT classes
from qtpy import QtCore

# QtWebKit is dropped in favour of QtWebEngine from Qt 5.6 on
try:
from qtpy.QtWebKit import QWebView as WebView
except ImportError:
from qtpy.QtWebEngineWidgets import QWebEngineView as WebView

# OSF connection interface
import QOpenScienceFramework.connection as osf
# Python 2 and 3 compatiblity settings
from QOpenScienceFramework.compat import *
from QOpenScienceFramework import dirname

osf_logo_path = os.path.join(dirname, 'img/cos-white2.png')

# Dummy function later to be replaced for translation
_ = lambda s: s

class LoginWindow(WebView):
""" A Login window for the OSF """

# Login event is emitted after successfull login
logged_in = QtCore.pyqtSignal()
""" Event fired when user successfully logged in. """

def __init__(self, *args, **kwargs):
super(LoginWindow, self).__init__(*args, **kwargs)

try:
# Create Network Access Manager to listen to all outgoing
# HTTP requests. Necessary to work around the WebKit 'bug' which
# causes it drop url fragments, and thus the access_token that the
# OSF Oauth system returns
self.nam = self.page().networkAccessManager()

# Connect event that is fired if a HTTP request is completed.
self.nam.finished.connect(self.checkResponse)
except:
pass
# Connect event that is fired if a HTTP request is completed.
# self.finished.connect(self.checkResponse)

# Connect event that is fired after an URL is changed
# (does not fire on 301 redirects, hence the requirement of the NAM)
self.urlChanged.connect(self.check_URL)

def checkResponse(self, reply):
"""Callback function. Do not use directly.
Callback for NetworkRequestManager.finished event
used to check if OAuth2 is redirecting to a link containing the token
string. This is necessary for the QtWebKit module, because it drops
fragments after being redirect to a different URL. QWebEngine uses the
check_URL function to check for the token fragment
Parameters
----------
reply : QtNetwork.QNetworkReply
The response object provided by NetworkRequestManager
"""
request = reply.request()
# Get the HTTP statuscode for this response
statuscode = reply.attribute(request.HttpStatusCodeAttribute)
# The accesstoken is given with a 302 statuscode to redirect

# Stop if statuscode is not 302 (HTTP Redirect)
if statuscode != 302:
return

redirectUrl = reply.attribute(request.RedirectionTargetAttribute)
if not redirectUrl.hasFragment():
return

r_url = redirectUrl.toString()
if osf.settings['redirect_uri'] in r_url:
try:
self.token = osf.parse_token_from_url(r_url)
except ValueError as e:
logging.warning(e)
else:
self.logged_in.emit()
self.hide()

def check_URL(self, url):
""" Callback function. Do not use directly.
Calback for urlChanged event.
Parameters
----------
command : url
New url, provided by the urlChanged event
"""
url_string = url.toString()

# QWebEngineView receives token here.
if url.hasFragment():
try:
self.token = osf.parse_token_from_url(url_string)
except ValueError as e:
logging.warning(e)
else:
self.logged_in.emit()
self.hide()
Loading

0 comments on commit 657be6e

Please sign in to comment.