This repository has been archived by the owner on Apr 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
gui.py
2831 lines (2096 loc) · 105 KB
/
gui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# coding: utf-8
import sys
import os
from PyQt5 import QtGui, QtSql, QtCore, QtWidgets
import datetime
import urllib
import fnmatch
import webbrowser
import requests
import platform
import validators
import collections as collec
import logging
import distutils.util
# Personal modules
from log import MyLog
from model import ModelPerso
from view import ViewPerso
from view_delegate import ViewDelegate
from worker import Worker
from predictor import Predictor
from settings import Settings
from advanced_search import AdvancedSearch
from tab import TabPerso
import functions
import hosts
from line_icon import ButtonLineIcon
from signing import Signing
from tuto import Tuto
from my_twit import MyTwit
from styles import MyStyles
from little_thread import LittleThread
from textbrowser import TextBrowserPerso
# To debug and profile. Comment for prod
# from memory_profiler import profile
# # DEBUG: do not show deprecation warningmport warningss
# import warnings
# warnings.filterwarnings("ignore", category=DeprecationWarning)
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
# Call processEvents regularly for the splash screen
start_time = datetime.datetime.now()
diff_time = start_time
super(MyWindow, self).__init__()
self.resource_dir, self.DATA_PATH = functions.getRightDirs()
# Check if the running ChemBrows is a frozen app
if getattr(sys, "frozen", False):
# The program is NOT in debug mod if it's frozen
self.debug_mod = False
# http://stackoverflow.com/questions/10293808/how-to-get-the-path-of-the-executing-frozen-script
# self.resource_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
# Create the user directory if it doesn't exist
os.makedirs(self.DATA_PATH, exist_ok=True)
# Create the 'journals' directory, user side
os.makedirs(os.path.join(self.DATA_PATH, 'journals/'),
exist_ok=True)
# Create the logger w/ the appropriate size
self.l = MyLog(os.path.join(self.DATA_PATH, "activity.log"))
self.l.info("This version of ChemBrows is frozen")
self.l.info("You are NOT in debug mode")
else:
# The program is in debug mod if it's not frozen
self.debug_mod = True
# Create the logger w/ the appropriate size
self.l = MyLog(os.path.join(self.DATA_PATH, "activity.log"),
size=100000000)
self.l.info("This version of ChemBrows is NOT frozen")
self.l.info("You are in debug mod")
# Set the logging level
# self.l.setLevel(logging.INFO)
self.l.setLevel(logging.DEBUG)
self.l.info('Resources dir: {}'.format(self.resource_dir))
self.l.info('Data dir: {}'.format(self.DATA_PATH))
self.l.debug('Working dir: {}'.format(os.getcwd()))
# self.l.setLevel(20)
self.l.info(QtWidgets.QApplication.libraryPaths())
self.l.info('Running {} {}'.format(platform.system(),
platform.release()))
self.l.info('Starting the program')
QtWidgets.qApp.setWindowIcon(QtGui.QIcon(
os.path.join(self.resource_dir, 'images', 'icon_main.png')))
# Display a splash screen when booting
# http://eli.thegreenplace.net/2009/05/09/creating-splash-screens-in-pyqt
# CAREFUL, there is a bug with the splash screen
# https://bugreports.qt.io/browse/QTBUG-24910
splash_pix = QtGui.QPixmap(os.path.join(self.resource_dir, 'images',
'splash.png'))
self.splash = QtWidgets.QSplashScreen(splash_pix,
QtCore.Qt.WindowStaysOnTopHint)
self.splash.show()
QtWidgets.qApp.processEvents()
self.styles = MyStyles(QtWidgets.qApp)
# Bool to check if the program is collecting data
self.parsing = False
# Bool to check if the ui is locked for the user
self.blocking_ui = False
QtWidgets.qApp.installEventFilter(self)
# List to store the tags checked
self.tags_selected = []
# List to store all the views, models and proxies
self.list_tables_in_tabs = []
self.list_proxies_in_tabs = []
# Object to store options and preferences
self.options = QtCore.QSettings(os.path.join(self.DATA_PATH, 'config',
'options.ini'),
QtCore.QSettings.IniFormat)
# Look for updates
QtWidgets.qApp.processEvents()
self.upgrade()
self.l.debug("bootCheckList took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
QtWidgets.qApp.processEvents()
# Connect to the database & log the connection
self.connectionBdd()
self.defineActions()
self.l.debug("connectionBdd & defineActions took {}"
.format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
QtWidgets.qApp.processEvents()
self.correctionVersion()
self.l.debug("correctionVersion took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
# Create the GUI
QtWidgets.qApp.processEvents()
self.initUI()
self.l.debug("initUI took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
# Define the slots
QtWidgets.qApp.processEvents()
self.defineSlots()
self.l.debug("defineSlots took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
# Creates the journals buttons
QtWidgets.qApp.processEvents()
self.displayTags()
self.l.debug("displayTags took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
# Restore the settings
QtWidgets.qApp.processEvents()
self.restoreSettings()
self.l.debug("restoreSettings took {}".
format(datetime.datetime.now() - diff_time))
diff_time = datetime.datetime.now()
QtWidgets.qApp.processEvents()
# Show the window
self.show()
self.splash.finish(self)
self.l.debug("splash.finish() took {}".
format(datetime.datetime.now() - diff_time))
self.l.info("Boot took {}".
format(datetime.datetime.now() - start_time))
# Check if user_id present, and create some directories
self.finishBoot()
def justUpgraded(self):
"""Check if CB was just updated"""
version_pkg = functions.getVersion()
self.l.debug("Version pkg: {}".format(version_pkg))
# If no whatsnew key in options.ini, display whatsnew.
version = self.options.value("version", version_pkg, str)
self.l.debug("Stored version: {}".format(version))
self.options.setValue("version", version_pkg)
if version < version_pkg:
return True
else:
return False
def availableUpgrade(self):
"""Check on the server if an upgrade is available"""
local_ver = functions.getVersion()
self.l.debug("Local version: {}".format(local_ver))
try:
r = requests.get("http://chembrows.com/downloads/version.txt")
except Exception as e:
self.l.error("availableUpgrade: {}".format(e), exc_info=True)
return False
os_name = distutils.util.get_platform()
self.l.debug("OS name: {}".format(os_name))
if os_name == 'win-amd64':
platform = 'win'
elif os_name == 'linux-x86_64':
platform = 'nix'
elif "macosx" and "x86_64" in os_name:
platform = 'mac'
else:
self.l.error("availableUpgrade, unindentified platform")
return False
self.l.debug("Platform: {}".format(platform))
for line in r.text.split("\n"):
if platform in line:
remote_ver = line.split(':')[1].strip()
self.l.error("Remote version: {}".format(remote_ver))
return local_ver < remote_ver
def upgrade(self):
"""Performs some startup checks"""
# Check if the running ChemBrows is a frozen app
if self.debug_mod:
return
mes = """
A new version of ChemBrows is available.<br/>
You can download it from
<a href='http://www.chembrows.com/website/index.php?static2/downloads'>
www.chembrows.com</a>
""".replace(' ', '')
if self.availableUpgrade():
QtWidgets.QMessageBox.information(self, "New version available",
mes,
QtWidgets.QMessageBox.Ok)
if self.justUpgraded():
with open(os.path.join(self.resource_dir,
'config/whatsnew.txt'), 'r', encoding='utf-8') as f:
message = f.read()
QtWidgets.QMessageBox.information(self, "What is new ?",
message,
QtWidgets.QMessageBox.Ok)
def logConnection(self):
"""Originally, coded to perform check acces on the server. If
the programm doesn't go commercial, RENAME THIS METHOD.
For now, this method get the max id, used to know if incoming articles
are new"""
# Check if there is a user_id. If so, log the connection
user_id = self.options.value("user_id", None)
if user_id is None:
return
with open(os.path.join(self.resource_dir, 'config/version.txt'), 'r',
encoding='utf-8') as version_file:
version = version_file.read()
count_query = QtSql.QSqlQuery(self.bdd)
count_query.exec_("SELECT COUNT(id) FROM papers")
count_query.first()
nbr_entries = count_query.record().value(0)
self.l.info("Nbr of entries: {}".format(nbr_entries))
payload = {'nbr_entries': nbr_entries,
'journals': self.getJournalsToParse(),
'user_id': user_id,
'version': version,
}
try:
if self.debug_mod:
req = requests.post('http://chembrows.com/cgi-bin/log.py',
params=payload, timeout=1)
else:
req = requests.post('http://chembrows.com/cgi-bin/log.py',
params=payload, timeout=5)
self.l.info('Server response: {}'.format(req.text))
except Exception as e:
self.l.error("logConnection: {}".format(e), exc_info=True)
return
if "user_id unregistered" in req.text:
self.options.remove("user_id")
self.l.error("The user_id was wrong. Set it to None")
def correctionVersion(self):
"""Called during boot, to correct problems between versions"""
# Get articles in ToRead list, old option
ids_waited = self.options.value("ids_waited", [])
if ids_waited:
articles = {}
query = QtSql.QSqlQuery(self.bdd)
requete = "SELECT * FROM papers WHERE id IN ("
# Building the query
for each_id in ids_waited:
if each_id != ids_waited[-1]:
requete = requete + str(each_id) + ", "
else:
requete = requete + str(each_id) + ")"
query.exec_(requete)
while query.next():
record = query.record()
articles[record.value('id')] = record.value('new')
searches_saved = QtCore.QSettings(os.path.join(self.DATA_PATH,
"config",
"searches.ini"),
QtCore.QSettings.IniFormat)
# Store the articles and their read states in a dictionary
searches_saved.setValue("ToRead/articles", articles)
self.options.remove('ids_waited')
# Remove bool for dark background. Removed in version 0.9.9
self.options.remove('Window/dark')
def finishBoot(self):
"""Method to register a new user. When it is done,
start the tutorial"""
# Create the folder to store the graphical_abstracts if
# it doesn't exist
# http://stackoverflow.com/questions/12517451/python-automatically-creating-directories-with-file-output
os.makedirs(os.path.join(self.DATA_PATH, 'graphical_abstracts'),
exist_ok=True)
# Check if there is a user_id. If not, register the user
if self.options.value("user_id", None) is None:
sign = Signing(self)
# When the user is registered, start the tuto
sign.accepted.connect(lambda: Tuto(self))
def showAbout(self):
"""Shows a dialogBox w/ the version number"""
version = functions.getVersion()
mes = """
You are using ChemBrows {}<br/><br/>
Visit our web site: <a href='http://www.chembrows.com'>
www.chembrows.com</a><br/><br/>
To contact us: <a href="mailto:[email protected]">
[email protected]</a><br/><br/>
ChemBrows is released under the GNU GPL License.<br/><br/>
DISCLAIMER: depending on the nature of the contracts between the
professional institutions and the publishers, some users may not be
allowed to automatically collect articles' metadata via their
institution's Internet networks. ChemBrows' authors assume no liability
for users' failures to comply with these contracts.
""".replace(' ', '').format(version)
# Use this complicated messageBox to get clickable URLs
box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information,
'About ChemBrows', mes)
box.setTextFormat(QtCore.Qt.RichText)
box.setText(mes)
box.exec()
def connectionBdd(self):
"""Method to connect to the database. Creates it
if it does not exist"""
sql_driver_available = QtSql.QSqlDatabase.isDriverAvailable('QSQLITE')
self.l.debug(f"Sqlite driver availe: {sql_driver_available}")
if not os.path.exists(os.path.join(self.DATA_PATH, "fichiers.sqlite")):
self.l.info("db doesn't exist. Creating.")
# Set the database
self.bdd = QtSql.QSqlDatabase.addDatabase("QSQLITE")
self.bdd.setDatabaseName(os.path.join(self.DATA_PATH,
"fichiers.sqlite"))
# Check if the DB can be accessed. If not, display error message and return
if self.bdd.open():
self.l.debug("Connection to database: SUCESS")
else:
self.l.critical("Connection to database: FAIL" + db.lastError().text())
return
query = QtSql.QSqlQuery(self.bdd)
query.exec_("CREATE TABLE IF NOT EXISTS papers (id INTEGER PRIMARY KEY\
AUTOINCREMENT, percentage_match REAL, doi TEXT, title\
TEXT, date TEXT, journal TEXT, authors TEXT, abstract\
TEXT, graphical_abstract TEXT, liked INTEGER, url TEXT,\
new INTEGER, topic_simple TEXT, author_simple TEXT)")
if self.debug_mod:
query.exec_("CREATE TABLE IF NOT EXISTS debug\
(id INTEGER PRIMARY KEY AUTOINCREMENT, doi TEXT,\
title TEXT, journal TEXT, url TEXT)")
# Create the model for the new tab
self.model = ModelPerso(self)
# Changes are not effective immediately, but it doesn't matter
# because the view is updated each time a change is made
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.setTable("papers")
self.model.select()
count_query = QtSql.QSqlQuery(self.bdd)
count_query.exec_("SELECT COUNT(id) FROM papers")
count_query.first()
nbr_entries = count_query.record().value(0)
self.l.info("Nbr of entries: {}".format(nbr_entries))
count_query.exec_("SELECT MAX(id) FROM papers")
count_query.first()
max_id_for_new = count_query.record().value(0)
if type(max_id_for_new) is not int:
max_id_for_new = 0
self.l.info("Max id for new: {}".format(max_id_for_new))
def getJournalsToParse(self):
"""Get the journals checked in the settings window"""
# If no journals to parse in the settings,
# parse them all. So build a journals_to_parse list
# with all the journals
journals = self.options.value("journals_to_parse", [])
if not journals:
journals = []
for company in hosts.getCompanies():
journals += hosts.getJournals(company)[1]
self.options.remove("journals_to_parse")
self.options.setValue("journals_to_parse", journals)
return journals
def parse(self):
"""Method to start parsing the data"""
self.start_time = datetime.datetime.now()
self.parsing = True
self.blocking_ui = True
# Disables the parse action to avoid double start
self.parseAction.setEnabled(False)
journals_to_parse = self.getJournalsToParse()
# Create a dictionary w/ all the data concerning the journals
# implemented in the program: names, abbreviations, urls.
# Create a list of urls to parse data
self.urls = []
self.dict_journals = {}
for company in hosts.getCompanies():
data_company = hosts.getJournals(company)
self.dict_journals[company] = data_company
for abb, url in zip(data_company[1], data_company[2]):
if abb in journals_to_parse:
self.urls.append(url)
# Display a progress dialog box
self.progress = QtWidgets.QProgressDialog("Collecting in progress",
"Cancel", 0, 100, self)
self.progress.setWindowTitle("Collecting articles")
self.progress.setModal(True)
self.progress.canceled.connect(self.cancelRefresh)
self.progress.show()
self.urls_max = len(self.urls)
# Get the optimal nbr of thread. Will vary depending
# on the user's computer. 4 is the maximum
if QtCore.QThread.idealThreadCount() > 4:
max_nbr_threads = 4
else:
max_nbr_threads = QtCore.QThread.idealThreadCount()
self.l.debug("IdealThreadCount: {}".format(max_nbr_threads))
# max_nbr_threads = 1
# Counter to count the new entries in the database
self.counter_added = 0
self.l.debug("counter_added: {}".format(self.counter_added))
self.counter_updates = 0
self.counter_rejected = 0
self.counter_articles_failed = 0
self.counter_images_failed = 0
self.browsing_session = requests.session()
# List of failed dl of RSS feeds
self.list_failed_rss = []
# List to store the threads.
# The list is cleared when the method is started
self.list_threads = []
self.count_threads = 0
for i in range(max_nbr_threads):
try:
url = self.urls[i]
worker = Worker(self)
worker.url_feed = url
worker.finished.connect(self.checkThreads)
self.urls.remove(url)
self.list_threads.append(worker)
worker.start()
QtWidgets.qApp.processEvents()
except IndexError:
self.l.debug("parse, self.urls, IndexError")
break
# @profile
def checkThreads(self):
"""Method to check the state of each thread.
If all the threads are finished, enable the parse action.
This slot is called when a thread is finished, to start the
next one"""
if not self.parsing:
return
elapsed_time = datetime.datetime.now() - self.start_time
self.l.info(elapsed_time)
self.count_threads += 1
for worker in self.list_threads:
if worker.isFinished():
self.list_threads.remove(worker)
del worker
# Display the nbr of finished threads
self.l.info("Done: {}/{}".format(self.count_threads, self.urls_max))
self.l.debug("counter_added: {}".format(self.counter_added))
# # Display the progress of the parsing w/ the progress bar
percent = self.count_threads * 100 / self.urls_max
self.progress.setValue(round(percent, 0))
if percent >= 100:
self.progress.reset()
QtWidgets.qApp.processEvents()
if self.count_threads == self.urls_max:
self.l.info("{} new entries added to the database".
format(self.counter_added))
self.l.info("{} entries rejected".
format(self.counter_rejected))
self.l.info("{} attempts to update entries\n".
format(self.counter_updates))
# Display current nbr of articles in db
count_query = QtSql.QSqlQuery(self.bdd)
count_query.exec_("SELECT COUNT(id) FROM papers")
count_query.first()
nbr_entries = count_query.record().value(0)
self.l.info("Nbr of entries: {}".format(nbr_entries))
self.l.info("{} RSS feeds were not downloaded:".
format(len(self.list_failed_rss)))
for feed in self.list_failed_rss:
self.l.info(feed)
self.l.info("\n")
self.l.info("{} articles failed".
format(self.counter_articles_failed))
self.l.info("{} images failed".
format(self.counter_images_failed))
total_time = datetime.datetime.now() - self.start_time
self.l.info("Total refresh time: {}".
format(total_time))
# # TODO: checker cette instruction, should crash
if self.counter_added > 0:
self.l.info("Time per paper: {} seconds".
format(total_time.seconds / (self.counter_added + self.counter_updates)))
else:
self.l.info("Time per paper: irrelevant, 0 paper added")
self.calculatePercentageMatch()
self.parseAction.setEnabled(True)
self.l.info("Parsing data finished. Enabling parseAction")
# Update the view when a worker is finished
self.searchByButton()
self.updateCellSize()
table = self.list_tables_in_tabs[self.onglets.currentIndex()]
table.verticalScrollBar().setSliderPosition(0)
table.selectionModel().clearSelection()
else:
if self.urls:
self.l.debug("STARTING NEW THREAD")
worker = Worker(self)
worker.url_feed = self.urls[0]
worker.finished.connect(self.checkThreads)
self.urls.remove(worker.url_feed)
self.list_threads.append(worker)
worker.start()
QtWidgets.qApp.processEvents()
def cancelRefresh(self):
"""Slot to cancel the refresh process"""
# Set the parsing bool to false, block checkThreads
self.parsing = False
# Cancel all the futures of each worker
for worker in self.list_threads:
for future in worker.list_futures:
QtWidgets.qApp.processEvents()
if type(future) is not bool:
future.cancel()
self.l.debug("Killed all the futures for this worker")
# Display a smooth progress bar
self.progress = QtWidgets.QProgressDialog("Cancelling...", None, 0, 0,
self)
self.progress.setWindowTitle("Cancelling refresh")
self.progress.show()
while False in [worker.isFinished() for worker in self.list_threads]:
QtWidgets.qApp.processEvents()
self.progress.setLabelText("Loading notifications...")
# Start loadNotifications in a thread (CPU consumming),
# and display a smooth progressBar while in the function
# But only if some articles were collected
if self.counter_added > 0:
worker = LittleThread(self.loadNotifications)
worker.start()
while worker.isRunning():
QtWidgets.qApp.processEvents()
worker.sleep(0.5)
self.updateCellSize()
self.progress.reset()
self.parseAction.setEnabled(True)
self.blocking_ui = False
def defineActions(self):
"""On définit ici les actions du programme. Cette méthode est
appelée à la création de la classe"""
# Action to quit
self.exitAction = QtWidgets.QAction('&Quit', self)
self.exitAction.setShortcut('Ctrl+Q')
self.exitAction.setStatusTip("Quit")
self.exitAction.triggered.connect(self.closeEvent)
# Action to refresh the posts
self.parseAction = QtWidgets.QAction('&Refresh', self)
self.parseAction.setShortcut('F5')
self.parseAction.setToolTip("Refresh: download new posts")
self.parseAction.triggered.connect(self.parse)
# Action to calculate the percentages of match
self.calculatePercentageMatchAction = QtWidgets.QAction('&Percentages', self)
self.calculatePercentageMatchAction.setShortcut('F6')
self.calculatePercentageMatchAction.setToolTip("Re-calculate Hot Paperness")
self.calculatePercentageMatchAction.triggered.connect(lambda: self.calculatePercentageMatch(True))
# Action to like a post
self.toggleLikeAction = QtWidgets.QAction('Toggle like', self)
self.toggleLikeAction.setShortcut('L')
self.toggleLikeAction.triggered.connect(self.toggleLike)
# Action to open the post in browser
self.openInBrowserAction = QtWidgets.QAction('Open post in browser', self)
self.openInBrowserAction.triggered.connect(self.openInBrowser)
self.openInBrowserAction.setShortcut('Ctrl+W')
# Action to show a settings window
self.settingsAction = QtWidgets.QAction('Preferences', self)
self.settingsAction.triggered.connect(lambda: Settings(self))
self.tutoAction = QtWidgets.QAction('Tutorial', self)
self.tutoAction.triggered.connect(lambda: Tuto(self))
# Action to show a settings window
self.showAboutAction = QtWidgets.QAction('About', self)
self.showAboutAction.triggered.connect(self.showAbout)
# # Action so show new articles
# self.searchNewAction = QtWidgets.QAction('View unread', self)
# self.searchNewAction.setToolTip("Display unread articles")
# self.searchNewAction.triggered.connect(self.searchNew)
# Action to toggle the read state of an article
self.toggleReadAction = QtWidgets.QAction('Toggle read', self)
self.toggleReadAction.setShortcut('M')
self.toggleReadAction.triggered.connect(self.toggleRead)
# Action to change the sorting method of the views. In the menu
self.sortingPercentageAction = QtWidgets.QAction('By Hot Paperness', self, checkable=True)
self.sortingPercentageAction.triggered.connect(lambda: self.changeSortingMethod(0))
# Action to change the sorting method of the views. In the menu
self.sortingDateAction = QtWidgets.QAction('By date', self, checkable=True)
self.sortingDateAction.triggered.connect(lambda: self.changeSortingMethod(1))
# Action to change the sorting method of the views, reverse the results. In the menu
self.sortingReversedAction = QtWidgets.QAction('Reverse order', self, checkable=True)
self.sortingReversedAction.triggered.connect(lambda: self.changeSortingMethod(self.sorting_method, True))
# Action to change the sorting method of the views, reverse the results. In the menu
self.emptyWaitAction = QtWidgets.QAction('Empty to-read list', self)
self.emptyWaitAction.triggered.connect(self.emptyWait)
# Action add/remove a post of the to-read list. For the right click
self.toggleWaitAction = QtWidgets.QAction('Add/remove to to-read list', self)
self.toggleWaitAction.triggered.connect(self.toggleWait)
self.showLikesAction = QtWidgets.QAction('Show liked articles', self)
self.showLikesAction.triggered.connect(self.showLikes)
self.showReadAction = QtWidgets.QAction('Show read articles', self)
self.showReadAction.triggered.connect(self.showRead)
# Action to serve use as a separator
self.separatorAction = QtWidgets.QAction(self)
self.separatorAction.setSeparator(True)
def changeSortingMethod(self, method_nbr, reverse=None):
"""
Slot to change the sorting method of the
articles. Get an int as a parameter:
1 -> percentage match
0 -> date
reverse -> if True, descending order
"""
if method_nbr is None:
self.sorting_method = 1 - self.sorting_method
else:
# Set a class attribute, to save with the QSettings,
# to restore the check at boot
self.sorting_method = method_nbr
if self.sorting_method == 1:
self.sortingPercentageAction.setChecked(False)
self.sortingDateAction.setChecked(True)
self.button_sort_by.setText("Sort by Hot Paperness")
elif self.sorting_method == 0:
self.sortingPercentageAction.setChecked(True)
self.sortingDateAction.setChecked(False)
self.button_sort_by.setText("Sort by date")
if reverse is not None:
self.sorting_reversed = self.sortingReversedAction.isChecked()
self.searchByButton()
table = self.list_tables_in_tabs[self.onglets.currentIndex()]
table.verticalScrollBar().setSliderPosition(0)
table.selectionModel().clearSelection()
def showLikes(self):
"""Show liked articles"""
# Use the proxy to filter the column liked
proxy = self.list_proxies_in_tabs[self.onglets.currentIndex()]
proxy.setFilterRegExp(QtCore.QRegExp("[1]"))
proxy.setFilterKeyColumn(9)
# Get the maximum nbr of like articles
count_like_max = QtSql.QSqlQuery(self.bdd)
count_like_max.exec_("SELECT COUNT(id) FROM papers WHERE liked=1")
count_like_max.first()
nbr_likes = count_like_max.record().value(0)
# Load all the liked articles:
# Mandatory to avoid a bug: if there is no liked articles in the
# chunk of the loaded sql entries, can cause a scrolling bug
# We count the nbr_likes articles liked to try to optimize the
# query
while (proxy.canFetchMore(QtCore.QModelIndex()) and
proxy.rowCount() < nbr_likes):
proxy.fetchMore(QtCore.QModelIndex())
self.updateCellSize()
table = self.list_tables_in_tabs[self.onglets.currentIndex()]
table.verticalScrollBar().setSliderPosition(0)
table.selectionModel().clearSelection()
def showRead(self):
"""
Show read (new) articles
new=1, which means unread
This method works exactly like showLikes()
"""
# Use the proxy to filter the column 'new'
proxy = self.list_proxies_in_tabs[self.onglets.currentIndex()]
proxy.setFilterRegExp(QtCore.QRegExp("[0]"))
proxy.setFilterKeyColumn(11)
# Get the maximum nbr of unread articles
count_read_max = QtSql.QSqlQuery(self.bdd)
count_read_max.exec_("SELECT COUNT(id) FROM papers WHERE new=0")
count_read_max.first()
nbr_read = count_read_max.record().value(0)
while (proxy.canFetchMore(QtCore.QModelIndex()) and
proxy.rowCount() < nbr_read):
proxy.fetchMore(QtCore.QModelIndex())
self.updateCellSize()
table = self.list_tables_in_tabs[self.onglets.currentIndex()]
table.verticalScrollBar().setSliderPosition(0)
table.selectionModel().clearSelection()
# @profile
def closeEvent(self, event):
"""Method to perform actions before exiting.
Allows to save the prefs in a file"""
# http://stackoverflow.com/questions/9249500/
# pyside-pyqt-detect-if-user-trying-to-close-window
# Log connection
self.logConnection()
# Record the window state and appearance
self.options.beginGroup("Window")
# Reinitializing the keys
self.options.remove("")
self.l.debug("Saving windows state")
self.options.setValue("window_geometry", self.saveGeometry())
self.options.setValue("window_state", self.saveState())
# Save the state of the window's splitter
self.options.setValue("final_splitter", self.splitter2.saveState())
# Save the sorting method
self.options.setValue("sorting_method", self.sorting_method)
self.options.setValue("sorting_reversed", self.sorting_reversed)
# TODO
# self.options.setValue("dark", self.dark)
for index, each_table in enumerate(self.list_tables_in_tabs):
self.options.setValue("header_state{0}".format(index),
each_table.horizontalHeader().saveState())
self.options.endGroup()
searches_saved = QtCore.QSettings(os.path.join(self.DATA_PATH,
"config",
"searches.ini"),
QtCore.QSettings.IniFormat)
# Save the to-read list
if self.waiting_list.articles:
searches_saved.setValue("ToRead/articles",
list(self.waiting_list.articles.keys()))
else:
searches_saved.remove("ToRead/articles")
for index, each_table in enumerate(self.list_tables_in_tabs):
tab_title = self.onglets.tabText(index)
if tab_title != 'All articles':
searches_saved.setValue("{}/articles".format(tab_title),
each_table.articles)
# Be sure ini files finished their tasks
# Correct a bug
self.options.sync()
searches_saved.sync()
self.model.submitAll()
# Close the database connection
self.bdd.removeDatabase(self.DATA_PATH + "/fichiers.sqlite")
self.bdd.close()
QtWidgets.qApp.quit()
self.l.info("Closing the program")
# @profile
def loadNotifications(self, tab_number=None):
"""Method to find the number of unread articles,
for each search. Load a list of id, for the unread articles,
in each table. And a list of id, for the concerned articles, for
each table. tab_number is here to load the notifications only for
a particular tab, when loadNotifications is called after an update
from an AdvancedSearch window"""
self.l.debug("Starting loadNotifications")
count_query = QtSql.QSqlQuery(self.bdd)
count_query.setForwardOnly(True)
# Don't treat the articles if it's the main tab, it's