Debian Codegraph @

src/calibre/gui2/main_window.py

raw
1 # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
2
3 import gc
4 import os
5 import sys
6 import weakref
7
8 from qt.core import QAction, QIcon, QKeySequence, QMainWindow, QMenu, QMenuBar, QObject, Qt, QTimer, pyqtSignal
9
10 from calibre import as_unicode, prepare_string_for_xml, prints
11 from calibre.constants import iswindows
12 from calibre.gui2 import error_dialog
13 from calibre.utils.config import OptionParser
14 from calibre.utils.localization import _
15 from polyglot.io import PolyglotStringIO
16
17
18 def option_parser(
19 usage='''\
20 Usage: %prog [options]
21
22 Launch the Graphical User Interface
23 ''',
24 ):
25 parser = OptionParser(usage)
26 return parser
27
28
29 class GarbageCollector(QObject):
30 """
31 Disable automatic garbage collection and instead collect manually
32 every INTERVAL milliseconds.
33
34 This is done to ensure that garbage collection only happens in the GUI
35 thread, as otherwise Qt can crash.
36 """
37
38 INTERVAL = 5000
39
40 def __init__(self, parent, debug=False):
41 QObject.__init__(self, parent)
42 self.debug = debug
43
44 self.timer = QTimer(self)
45 self.timer.timeout.connect(self.check)
46
47 self.threshold = gc.get_threshold()
48 gc.disable()
49 self.timer.start(self.INTERVAL)
50 # gc.set_debug(gc.DEBUG_SAVEALL)
51
52 def check(self):
53 # return self.debug_cycles()
54 l0, l1, l2 = gc.get_count()
55 if self.debug:
56 print('gc_check called:', l0, l1, l2)
57 if l0 > self.threshold[0]:
58 num = gc.collect(0)
59 if self.debug:
60 print('collecting gen 0, found:', num, 'unreachable')
61 if l1 > self.threshold[1]:
62 num = gc.collect(1)
63 if self.debug:
64 print('collecting gen 1, found:', num, 'unreachable')
65 if l2 > self.threshold[2]:
66 num = gc.collect(2)
67 if self.debug:
68 print('collecting gen 2, found:', num, 'unreachable')
69
70 def debug_cycles(self):
71 gc.collect()
72 for obj in gc.garbage:
73 print(obj, repr(obj), type(obj))
74
75
76 class ExceptionHandler:
77 def __init__(self, main_window):
78 self.wref = weakref.ref(main_window)
79
80 def __call__(self, type, value, tb):
81 mw = self.wref()
82 if mw is not None:
83 mw.display_unhandled_exception.emit(type, value, tb)
84 else:
85 sys.__excepthook__(type, value, tb)
86
87
88 class MainWindow(QMainWindow):
89 ___menu_bar = None
90 ___menu = None
91 __actions = []
92 display_unhandled_exception = pyqtSignal(object, object, object)
93
94 @classmethod
95 def create_application_menubar(cls):
96 if not cls.__actions:
97 mb = QMenuBar(None)
98 menu = QMenu()
99 for action in cls.get_menubar_actions():
100 menu.addAction(action)
101 cls.__actions.append(action)
102 mb.addMenu(menu)
103 cls.___menu_bar = mb
104 cls.___menu = menu
105 return cls.__actions
106
107 @classmethod
108 def get_menubar_actions(cls):
109 preferences_action = QAction(QIcon.ic('config.png'), _('&Preferences'), None)
110 quit_action = QAction(QIcon.ic('window-close.png'), _('&Quit'), None)
111 preferences_action.setMenuRole(QAction.MenuRole.PreferencesRole)
112 quit_action.setMenuRole(QAction.MenuRole.QuitRole)
113 return preferences_action, quit_action
114
115 @property
116 def native_menubar(self):
117 return self.___menu_bar
118
119 def __init__(self, opts=None, parent=None, disable_automatic_gc=False):
120 QMainWindow.__init__(self, parent)
121 self.display_unhandled_exception.connect(self.unhandled_exception, type=Qt.ConnectionType.QueuedConnection)
122 if disable_automatic_gc:
123 self._gc = GarbageCollector(self, debug=False)
124
125 def enable_garbage_collection(self, enabled=True):
126 if hasattr(self, '_gc'):
127 self._gc.timer.blockSignals(not enabled)
128 else:
129 gc.enable() if enabled else gc.disable()
130
131 def set_exception_handler(self):
132 sys.excepthook = ExceptionHandler(self)
133
134 def show_possible_sharing_violation(self, e: Exception, det_msg: str = '') -> bool:
135 if not iswindows or not isinstance(e, OSError):
136 return False
137 import errno
138
139 from calibre_extensions import winutil
140
141 if not (e.winerror == winutil.ERROR_SHARING_VIOLATION or e.errno == errno.EACCES or isinstance(e, PermissionError)):
142 return False
143 msg = getattr(e, 'locking_violation_msg', '')
144 if msg:
145 msg = msg.strip() + ' '
146 fname = e.filename
147
148 def no_processes_found() -> bool:
149 is_folder = fname and os.path.isdir(fname)
150 if e.winerror == winutil.ERROR_SHARING_VIOLATION:
151 if fname:
152 if is_folder:
153 dmsg = _('The folder "{}" is opened in another program, so calibre cannot access it.').format(fname)
154 else:
155 dmsg = _('The file "{}" is opened in another program, so calibre cannot access it.').format(fname)
156 elif is_folder:
157 dmsg = _('A folder is open in another program so calibre cannot access it.')
158 else:
159 dmsg = _('A file is open in another program so calibre cannot access it.')
160 if is_folder:
161 dmsg += _(
162 'This is usually caused by leaving Windows explorer or a similar file manager open'
163 ' to a folder in the calibre library. Close Windows explorer and retry.'
164 )
165 else:
166 dmsg += _(
167 'This is usually caused by software such as antivirus or file sync (aka DropBox and similar)'
168 ' accessing files in the calibre library folder at the same time as calibre. Try excluding'
169 ' the calibre library folder from such software.'
170 )
171 error_dialog(self, _('Cannot open file or folder as it is in use'), msg + dmsg, det_msg=det_msg, show=True)
172 return True
173 if msg:
174 if fname:
175 dmsg = _('Permission was denied by the operating system when calibre tried to access the file: "{0}".').format(fname)
176 else:
177 dmsg = _('Permission was denied by the operating system when calibre tried to access a file.')
178 dmsg += ' ' + _('This means either that the permissions on the file or its parent folder are incorrect or the file is open in another program.')
179 error_dialog(self, _('Cannot open file or folder'), msg + dmsg, det_msg=det_msg, show=True)
180 return True
181 return False
182
183 if not hasattr(winutil, 'get_processes_using_files'):
184 return no_processes_found() # running from source
185 if not e.filename and not e.filename2:
186 return no_processes_found()
187 if e.filename and isinstance(e.filename, str):
188 if os.path.isdir(e.filename):
189 return no_processes_found()
190 try:
191 p = winutil.get_processes_using_files(e.filename)
192 except OSError:
193 return no_processes_found()
194 if not p and e.filename2 and isinstance(e.filename2, str):
195 if os.path.isdir(e.filename2):
196 return no_processes_found()
197 try:
198 p = winutil.get_processes_using_files(e.filename2)
199 except OSError:
200 return no_processes_found()
201 fname = e.filename2
202 if not p:
203 return no_processes_found()
204
205 path_map = {x['path']: x for x in p}
206 is_folder = fname and os.path.isdir(fname)
207 if is_folder:
208 dmsg = _('Could not open the folder: "{}". It is already opened in the following programs:').format(fname)
209 else:
210 dmsg = _('Could not open the file: "{}". It is already opened in the following programs:').format(fname)
211 for path, x in path_map.items():
212 dmsg += '<div>' + prepare_string_for_xml(f'{x["app_name"]}: {path}')
213 msg = prepare_string_for_xml(msg)
214 error_dialog(self, _('Cannot open file or folder as it is in use'), '<p>' + msg + dmsg, det_msg=det_msg, show=True)
215 return True
216
217 def unhandled_exception(self, exc_type, value, tb):
218 if exc_type is KeyboardInterrupt:
219 return
220 import traceback
221
222 try:
223 sio = PolyglotStringIO(errors='replace')
224 try:
225 from calibre.debug import print_basic_debug_info
226
227 print_basic_debug_info(out=sio)
228 except Exception:
229 pass
230 traceback.print_exception(exc_type, value, tb, file=sio)
231 if getattr(value, 'locking_debug_msg', None):
232 prints(value.locking_debug_msg, file=sio)
233 fe = sio.getvalue()
234 prints(fe, file=sys.stderr)
235 try:
236 if self.show_possible_sharing_violation(value, det_msg=fe):
237 return
238 except Exception:
239 traceback.print_exc()
240 msg = f'<b>{exc_type.__name__}</b>:' + prepare_string_for_xml(as_unicode(value))
241 error_dialog(self, _('Unhandled exception'), msg, det_msg=fe, show=True)
242 except BaseException:
243 pass
244 except Exception:
245 pass
246
247
248 def clone_menu(menu):
249 # This is needed to workaround a bug in Qt 5.5+ and Unity. When the same
250 # QAction object is used in both a QMenuBar and a QMenu, sub-menus of the
251 # QMenu flicker when rendered under Unity.
252
253 def clone_action(ac, parent):
254 if ac.isSeparator():
255 ans = QAction(parent)
256 ans.setSeparator(True)
257 return ans
258 sc = ac.shortcut()
259 sc = '' if sc.isEmpty() else sc.toString(QKeySequence.SequenceFormat.NativeText)
260 text = ac.text()
261 if '\t' not in text:
262 text += '\t' + sc
263 ans = QAction(ac.icon(), text, parent)
264 ans.triggered.connect(ac.trigger)
265 ans.setEnabled(ac.isEnabled())
266 ans.setStatusTip(ac.statusTip())
267 ans.setVisible(ac.isVisible())
268 ans.setCheckable(ac.isCheckable())
269 ans.setChecked(ac.isChecked())
270 return ans
271
272 def clone_one_menu(m):
273 m.aboutToShow.emit()
274 ans = QMenu(m.parent())
275 ans.hovered.connect(m.hovered.emit)
276 for ac in m.actions():
277 cac = clone_action(ac, ans)
278 ans.addAction(cac)
279 m = ac.menu()
280 if m is not None:
281 cac.setMenu(clone_menu(m))
282 return ans
283
284 return clone_one_menu(menu)