Skip to content

Commit

Permalink
Merge pull request #37 from fukatani/fix-next-problem
Browse files Browse the repository at this point in the history
Fix next problem
  • Loading branch information
fukatani authored Oct 20, 2019
2 parents e2df805 + 635bae6 commit e59e72c
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 45 deletions.
145 changes: 106 additions & 39 deletions rujaion/webview_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineScript

from onlinejudge.dispatch import service_from_url
from onlinejudge import dispatch
from onlinejudge._implementation.utils import (
default_cookie_path,
with_cookiejar,
new_session_with_our_user_agent,
)
from PyQt5.QtCore import QThread
from PyQt5.QtNetwork import QNetworkCookie

# Many of source is copied from https://qiita.com/montblanc18/items/88d0b639de86b7cac613
Expand Down Expand Up @@ -92,11 +93,64 @@ def __init__(self, *args, **kwargs):

def contextMenuEvent(self, a0: QtGui.QContextMenuEvent) -> None:
menu = QtWidgets.QMenu()
menu.addAction(u"Go Next Task", self.parent().goNextTask)
menu.addAction(u"Go Previous Task", self.parent().goPreviousTask)
if self.parent().next_prev_updater.next is not None:
menu.addAction(u"Go Next Task", self.parent().goNextTask)
if self.parent().next_prev_updater.prev is not None:
menu.addAction(u"Go Previous Task", self.parent().goPreviousTask)
if self.selectedText():
menu.addAction(u"View Graph", self.viewGraph)
menu.addAction(u"Back", self.back)
menu.addSeparator()
if self.parent().next_prev_updater.problems is not None:
problems = self.parent().next_prev_updater.problems
for i, problem_url in enumerate(problems):
problem_id = problem_url.split("/")[-1]
# I know this is not good code.
# But commented out code does not works
# menu.addAction(
# u"Go to {}".format(problem_id),
# lambda: self.parent().changePage(problem)
# )
if i == 0:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[0]),
)
elif i == 1:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[1]),
)
elif i == 2:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[2]),
)
elif i == 3:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[3]),
)
elif i == 4:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[4]),
)
elif i == 5:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[5]),
)
elif i == 6:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[6]),
)
elif i == 7:
menu.addAction(
u"Go to {}".format(problem_id),
lambda: self.parent().changePage(problems[7]),
)
menu.exec(a0.globalPos())

def runScript(self) -> None:
Expand Down Expand Up @@ -140,10 +194,6 @@ def viewGraph(self) -> None:
url = "https://hello-world-494ec.firebaseapp.com/?format=true&directed=false&weighted={0}&indexed={1}&data={2}".format(
weighted, indexed, graph_query
)
# import webbrowser
# webbrowser.open_new_tab(url)
# self.load(url)
# self.page().runJavaScript("window.scrollTo(-500, -500);")
try:
subprocess.Popen(["sensible-browser", url])
except subprocess.TimeoutExpired:
Expand All @@ -158,7 +208,6 @@ def __init__(self, parent=None, *args):
self.browser.setWindowTitle("Task")
self.url_edit = QtWidgets.QLineEdit()
self.url_edit.returnPressed.connect(self.loadPage)
self.browser.urlChanged.connect(self.updateCurrentUrl)
session = new_session_with_our_user_agent()
self.browser.page().profile().setHttpUserAgent(session.headers["User-Agent"])
self.browser.page().profile().cookieStore().cookieAdded.connect(
Expand All @@ -171,12 +220,16 @@ def __init__(self, parent=None, *args):
grid.addWidget(self.browser, 1, 0, 5, 15)
self.setLayout(grid)
self.resize(800, 800)
self.next_prev_updater = NextPreviousProblemUpdater()

def download_task(self):
self.next_prev_updater.url = self.browser.url().toString()
self.next_prev_updater.start()
self.url_edit.setText(self.browser.url().toString())
self.parent().parent().download(self.url_edit.text())

def loadPage(self):
self.next_prev_updater.reset()
if self.url_edit.text():
self.browser.load(QUrl(self.url_edit.text()))

Expand All @@ -189,59 +242,73 @@ def goNextTask(self):
ex.
https://atcoder.jp/contests/cpsco2019-s2/tasks/cpsco2019_s2_e ->
https://atcoder.jp/contests/cpsco2019-s2/tasks/cpsco2019_s2_f
This function is note tested except AtCoder.
"""
current_url = self.browser.url().toString().split("?")
if current_url[0].split("/")[-1].isdecimal(): # yukicoder
words = current_url[0].split("/")
words[-1] = str(int(words[-1]) + 1)
current_url[0] = "/".join(words)
else:
if current_url[0][-1] == "z":
return
current_url[0] = current_url[0][:-1] + chr(ord(current_url[0][-1]) + 1)
self.changePage("?".join(current_url))
if self.next_prev_updater.next is not None:
self.changePage(self.next_prev_updater.next)

def goPreviousTask(self):
""" Go previous contest task.
ex.
https://atcoder.jp/contests/cpsco2019-s2/tasks/cpsco2019_s2_b ->
https://atcoder.jp/contests/cpsco2019-s2/tasks/cpsco2019_s2_a
This function is note tested except AtCoder.
"""
current_url = self.browser.url().toString().split("?")
if current_url.split("/")[-1].isdecimal(): # yukicoder
words = current_url[0].split("/")
words[-1] = str(int(words[-1]) - 1)
current_url[0] = "/".join(words)
else:
if current_url[0][-1] == "a":
return
current_url[0] = current_url[0][:-1] + chr(ord(current_url[0][-1]) + 1)
self.changePage("?".join(current_url))

def updateCurrentUrl(self):
""" Rewriting url_edit when you move different web page.
"""
self.url_edit.clear()
self.url_edit.insert(self.browser.url().toString())
if self.next_prev_updater.prev is not None:
self.changePage(self.next_prev_updater.prev)

def focusOnUrlEdit(self):
self.url_edit.setFocus()
self.url_edit.selectAll()

def handleCookieAdded(self, cookie: QNetworkCookie):
url = self.browser.url().toString()
if service_from_url(url):
if dispatch.service_from_url(url):
py_cookie = toPyCookie(cookie)
with with_cookiejar(
new_session_with_our_user_agent(), path=default_cookie_path
) as sess:
sess.cookies.set_cookie(py_cookie)


class NextPreviousProblemUpdater(QThread):
def __init__(self):
super().__init__()
self.url = ""
self.next = None
self.prev = None
self.problems = None

def reset(self):
self.next = None
self.prev = None
# self.problems = None

def run(self):
cur_problem = dispatch.problem_from_url(self.url)
if cur_problem is None:
return
if cur_problem.get_service().get_name() == "yukicoder":
words = self.url.split("?")
words = words[0].split("/")
prev_words = words.copy()
prev_words[-1] = str(int(words[-1]) - 1)
next_words = words.copy()
next_words[-1] = str(int(words[-1]) + 1)
self.prev = "/".join(prev_words)
self.next = "/".join(next_words)
return
try:
contest = cur_problem.get_contest()
problems = contest.list_problems()
for i, problem in enumerate(problems):
if problem == cur_problem:
self.prev = problems[i - 1].get_url()
self.next = problems[(i + 1) % len(problems)].get_url()
break
self.problems = [problem_url.get_url() for problem_url in problems]
except Exception:
pass


def toPyCookie(qt_cookie: QNetworkCookie) -> Cookie:
port = None
port_specified = False
Expand Down
8 changes: 2 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ def load_module(module_path):
"pandas",
],
packages=find_packages(exclude=("docker", "doc")),
package_data={ 'rujaion' : ['resources/*'], },
entry_points={
'console_scripts': [
'rujaion = rujaion.rujaion_main:main',
],
},
package_data={"rujaion": ["resources/*"]},
entry_points={"console_scripts": ["rujaion = rujaion.rujaion_main:main"]},
)

0 comments on commit e59e72c

Please sign in to comment.