| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
""" |
| 5 |
Job management. |
| 6 |
""" |
| 7 |
|
| 8 |
import time |
| 9 |
from queue import Empty, Queue |
| 10 |
|
| 11 |
from qt.core import ( |
| 12 |
QAbstractItemDelegate, |
| 13 |
QAbstractTableModel, |
| 14 |
QAction, |
| 15 |
QApplication, |
| 16 |
QByteArray, |
| 17 |
QCoreApplication, |
| 18 |
QDialog, |
| 19 |
QDialogButtonBox, |
| 20 |
QEvent, |
| 21 |
QHBoxLayout, |
| 22 |
QIcon, |
| 23 |
QItemSelectionModel, |
| 24 |
QKeySequence, |
| 25 |
QLabel, |
| 26 |
QModelIndex, |
| 27 |
QPlainTextEdit, |
| 28 |
QSize, |
| 29 |
QSizePolicy, |
| 30 |
QSortFilterProxyModel, |
| 31 |
QStyle, |
| 32 |
QStyleOption, |
| 33 |
QStyleOptionProgressBar, |
| 34 |
QStylePainter, |
| 35 |
Qt, |
| 36 |
QTextBrowser, |
| 37 |
QTimer, |
| 38 |
QToolTip, |
| 39 |
QVBoxLayout, |
| 40 |
QWidget, |
| 41 |
pyqtSignal, |
| 42 |
) |
| 43 |
|
| 44 |
from calibre import __appname__, as_unicode, strftime |
| 45 |
from calibre.constants import isbsd, islinux |
| 46 |
from calibre.db.utils import human_readable_interval |
| 47 |
from calibre.gui2 import Dispatcher, config, error_dialog, gprefs, qapplication_or_fail, question_dialog |
| 48 |
from calibre.gui2.device import DeviceJob |
| 49 |
from calibre.gui2.dialogs.jobs_ui import Ui_JobsDialog |
| 50 |
from calibre.gui2.progress_indicator import ProgressIndicator |
| 51 |
from calibre.gui2.threaded_jobs import ThreadedJob, ThreadedJobServer |
| 52 |
from calibre.gui2.widgets2 import Dialog |
| 53 |
from calibre.startup import connect_lambda |
| 54 |
from calibre.utils.icu import lower |
| 55 |
from calibre.utils.ipc.job import ParallelJob |
| 56 |
from calibre.utils.ipc.server import Server |
| 57 |
from calibre.utils.localization import _, ngettext |
| 58 |
from calibre.utils.search_query_parser import ParseException, SearchQueryParser |
| 59 |
|
| 60 |
|
| 61 |
class AdaptSQP(SearchQueryParser): |
| 62 |
def __init__(self, *args, **kwargs): |
| 63 |
pass |
| 64 |
|
| 65 |
|
| 66 |
class JobManager(QAbstractTableModel, AdaptSQP): |
| 67 |
job_added = pyqtSignal(int) |
| 68 |
job_done = pyqtSignal(int) |
| 69 |
|
| 70 |
def __init__(self): |
| 71 |
self.header_titles = _('Job'), _('Status'), _('Progress'), _('Running time'), _('Start time') |
| 72 |
QAbstractTableModel.__init__(self) |
| 73 |
SearchQueryParser.__init__(self, ['all']) |
| 74 |
|
| 75 |
self.wait_icon = QIcon.ic('jobs.png') |
| 76 |
self.running_icon = QIcon.ic('exec.png') |
| 77 |
self.error_icon = QIcon.ic('dialog_error.png') |
| 78 |
self.done_icon = QIcon.ic('ok.png') |
| 79 |
|
| 80 |
self.jobs = [] |
| 81 |
self.add_job = Dispatcher(self._add_job) |
| 82 |
self.server = Server(limit=config['worker_limit'] // 2, enforce_cpu_limit=config['enforce_cpu_limit']) |
| 83 |
self.threaded_server = ThreadedJobServer() |
| 84 |
self.changed_queue = Queue() |
| 85 |
|
| 86 |
self.timer = QTimer(self) |
| 87 |
self.timer.timeout.connect(self.update, type=Qt.ConnectionType.QueuedConnection) |
| 88 |
self.timer.start(1000) |
| 89 |
|
| 90 |
def columnCount(self, parent=QModelIndex()): |
| 91 |
return 5 |
| 92 |
|
| 93 |
def rowCount(self, parent=QModelIndex()): |
| 94 |
return len(self.jobs) |
| 95 |
|
| 96 |
def headerData(self, section, orientation, role=None): |
| 97 |
if role == Qt.ItemDataRole.DisplayRole: |
| 98 |
if orientation == Qt.Orientation.Horizontal: |
| 99 |
try: |
| 100 |
return self.header_titles[section] |
| 101 |
except Exception: |
| 102 |
pass |
| 103 |
return str(section + 1) |
| 104 |
|
| 105 |
def show_tooltip(self, arg): |
| 106 |
widget, pos = arg |
| 107 |
QToolTip.showText(pos, self.get_tooltip()) |
| 108 |
|
| 109 |
def get_tooltip(self): |
| 110 |
running_jobs = [j for j in self.jobs if j.run_state == j.RUNNING] |
| 111 |
waiting_jobs = [j for j in self.jobs if j.run_state == j.WAITING] |
| 112 |
lines = [ngettext('There is a running job:', 'There are {} running jobs:', len(running_jobs)).format(len(running_jobs))] |
| 113 |
for job in running_jobs: |
| 114 |
desc = job.description |
| 115 |
if not desc: |
| 116 |
desc = _('Unknown job') |
| 117 |
p = 100.0 if job.is_finished else job.percent |
| 118 |
lines.append(f'{desc}: {p:.0f}% done') |
| 119 |
l = ngettext('There is a waiting job', 'There are {} waiting jobs', len(waiting_jobs)).format(len(waiting_jobs)) |
| 120 |
lines.extend(['', l]) |
| 121 |
for job in waiting_jobs: |
| 122 |
desc = job.description |
| 123 |
if not desc: |
| 124 |
desc = _('Unknown job') |
| 125 |
lines.append(desc) |
| 126 |
return '\n'.join(['calibre', ''] + lines) |
| 127 |
|
| 128 |
def data(self, index, role=None): |
| 129 |
try: |
| 130 |
if role not in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.DecorationRole): |
| 131 |
return None |
| 132 |
row, col = index.row(), index.column() |
| 133 |
job = self.jobs[row] |
| 134 |
|
| 135 |
if role == Qt.ItemDataRole.DisplayRole: |
| 136 |
if col == 0: |
| 137 |
desc = job.description |
| 138 |
if not desc: |
| 139 |
desc = _('Unknown job') |
| 140 |
return desc |
| 141 |
if col == 1: |
| 142 |
return job.status_text |
| 143 |
if col == 2: |
| 144 |
p = 100.0 if job.is_finished else job.percent |
| 145 |
return p |
| 146 |
if col == 3: |
| 147 |
rtime = job.running_time |
| 148 |
if rtime is None: |
| 149 |
return None |
| 150 |
return human_readable_interval(rtime) |
| 151 |
if col == 4 and job.start_time is not None: |
| 152 |
return strftime('%H:%M -- %d %b', time.localtime(job.start_time)) |
| 153 |
if role == Qt.ItemDataRole.DecorationRole and col == 0: |
| 154 |
state = job.run_state |
| 155 |
if state == job.WAITING: |
| 156 |
return self.wait_icon |
| 157 |
if state == job.RUNNING: |
| 158 |
return self.running_icon |
| 159 |
if job.killed or job.failed: |
| 160 |
return self.error_icon |
| 161 |
return self.done_icon |
| 162 |
except Exception: |
| 163 |
import traceback |
| 164 |
|
| 165 |
traceback.print_exc() |
| 166 |
return None |
| 167 |
|
| 168 |
def update(self): |
| 169 |
try: |
| 170 |
self._update() |
| 171 |
except BaseException: |
| 172 |
import traceback |
| 173 |
|
| 174 |
traceback.print_exc() |
| 175 |
|
| 176 |
def _update(self): |
| 177 |
|
| 178 |
for i, j in enumerate(self.jobs): |
| 179 |
if j.run_state == j.RUNNING: |
| 180 |
idx = self.index(i, 3) |
| 181 |
self.dataChanged.emit(idx, idx) |
| 182 |
|
| 183 |
|
| 184 |
jobs = set() |
| 185 |
while True: |
| 186 |
try: |
| 187 |
jobs.add(self.server.changed_jobs_queue.get_nowait()) |
| 188 |
except Empty: |
| 189 |
break |
| 190 |
|
| 191 |
|
| 192 |
while True: |
| 193 |
try: |
| 194 |
jobs.add(self.changed_queue.get_nowait()) |
| 195 |
except Empty: |
| 196 |
break |
| 197 |
|
| 198 |
|
| 199 |
while True: |
| 200 |
try: |
| 201 |
jobs.add(self.threaded_server.changed_jobs.get_nowait()) |
| 202 |
except Empty: |
| 203 |
break |
| 204 |
|
| 205 |
if jobs: |
| 206 |
needs_reset = False |
| 207 |
for job in jobs: |
| 208 |
orig_state = job.run_state |
| 209 |
job.update() |
| 210 |
if orig_state != job.run_state: |
| 211 |
needs_reset = True |
| 212 |
if job.is_finished: |
| 213 |
self.job_done.emit(len(self.unfinished_jobs())) |
| 214 |
if needs_reset: |
| 215 |
self.modelAboutToBeReset.emit() |
| 216 |
self.jobs.sort() |
| 217 |
self.modelReset.emit() |
| 218 |
else: |
| 219 |
for job in jobs: |
| 220 |
idx = self.jobs.index(job) |
| 221 |
self.dataChanged.emit(self.index(idx, 0), self.index(idx, 3)) |
| 222 |
|
| 223 |
|
| 224 |
try: |
| 225 |
wmax_time = gprefs['worker_max_time'] * 60 |
| 226 |
except Exception: |
| 227 |
wmax_time = 0 |
| 228 |
|
| 229 |
if wmax_time > 0: |
| 230 |
for job in self.jobs: |
| 231 |
if isinstance(job, ParallelJob): |
| 232 |
rtime = job.running_time |
| 233 |
if rtime is not None and rtime > wmax_time and job.duration is None: |
| 234 |
job.timed_out = True |
| 235 |
self.server.kill_job(job) |
| 236 |
|
| 237 |
def _add_job(self, job): |
| 238 |
self.modelAboutToBeReset.emit() |
| 239 |
self.jobs.append(job) |
| 240 |
self.jobs.sort() |
| 241 |
self.job_added.emit(len(self.unfinished_jobs())) |
| 242 |
self.modelReset.emit() |
| 243 |
|
| 244 |
def done_jobs(self): |
| 245 |
return [j for j in self.jobs if j.is_finished] |
| 246 |
|
| 247 |
def unfinished_jobs(self): |
| 248 |
return [j for j in self.jobs if not j.is_finished] |
| 249 |
|
| 250 |
def row_to_job(self, row): |
| 251 |
return self.jobs[row] |
| 252 |
|
| 253 |
def rows_to_jobs(self, rows): |
| 254 |
return [self.jobs[row] for row in rows] |
| 255 |
|
| 256 |
def has_device_jobs(self, queued_also=False): |
| 257 |
for job in self.jobs: |
| 258 |
if isinstance(job, DeviceJob): |
| 259 |
if job.duration is None: |
| 260 |
if job.is_running or queued_also: |
| 261 |
return True |
| 262 |
return False |
| 263 |
|
| 264 |
def has_jobs(self): |
| 265 |
for job in self.jobs: |
| 266 |
if job.is_running: |
| 267 |
return True |
| 268 |
return False |
| 269 |
|
| 270 |
def run_job(self, done, name, args=[], kwargs={}, description='', core_usage=1): |
| 271 |
job = ParallelJob(name, description, done, args=args, kwargs=kwargs) |
| 272 |
job.core_usage = core_usage |
| 273 |
self.add_job(job) |
| 274 |
self.server.add_job(job) |
| 275 |
return job |
| 276 |
|
| 277 |
def run_threaded_job(self, job): |
| 278 |
self.add_job(job) |
| 279 |
self.threaded_server.add_job(job) |
| 280 |
|
| 281 |
def launch_gui_app(self, name, args=(), kwargs=None, description=''): |
| 282 |
job = ParallelJob(name, description, lambda x: x, args=list(args), kwargs=kwargs or {}) |
| 283 |
self.server.run_job(job, gui=True, redirect_output=False) |
| 284 |
|
| 285 |
def _kill_job(self, job): |
| 286 |
if isinstance(job, ParallelJob): |
| 287 |
self.server.kill_job(job) |
| 288 |
elif isinstance(job, ThreadedJob): |
| 289 |
self.threaded_server.kill_job(job) |
| 290 |
else: |
| 291 |
job.kill_on_start = True |
| 292 |
|
| 293 |
def hide_jobs(self, rows): |
| 294 |
for r in rows: |
| 295 |
self.jobs[r].hidden_in_gui = True |
| 296 |
for r in rows: |
| 297 |
self.dataChanged.emit(self.index(r, 0), self.index(r, 0)) |
| 298 |
|
| 299 |
def show_hidden_jobs(self): |
| 300 |
for j in self.jobs: |
| 301 |
j.hidden_in_gui = False |
| 302 |
for r in range(len(self.jobs)): |
| 303 |
self.dataChanged.emit(self.index(r, 0), self.index(r, 0)) |
| 304 |
|
| 305 |
def kill_job(self, job, view): |
| 306 |
if isinstance(job, DeviceJob): |
| 307 |
return error_dialog(view, _('Cannot kill job'), _('Cannot kill jobs that communicate with the device')).exec() |
| 308 |
if job.duration is not None: |
| 309 |
return error_dialog(view, _('Cannot kill job'), _('Job has already run')).exec() |
| 310 |
if not getattr(job, 'killable', True): |
| 311 |
return error_dialog(view, _('Cannot kill job'), _('This job cannot be stopped'), show=True) |
| 312 |
self._kill_job(job) |
| 313 |
|
| 314 |
def kill_multiple_jobs(self, jobs, view): |
| 315 |
devjobs = [j for j in jobs if isinstance(j, DeviceJob)] |
| 316 |
if devjobs: |
| 317 |
error_dialog(view, _('Cannot kill job'), _('Cannot kill jobs that communicate with the device')).exec() |
| 318 |
jobs = [j for j in jobs if not isinstance(j, DeviceJob)] |
| 319 |
jobs = [j for j in jobs if j.duration is None] |
| 320 |
unkillable = [j for j in jobs if not getattr(j, 'killable', True)] |
| 321 |
if unkillable: |
| 322 |
names = '\n'.join(as_unicode(j.description) for j in unkillable) |
| 323 |
error_dialog( |
| 324 |
view, |
| 325 |
_('Cannot kill job'), |
| 326 |
_('Some of the jobs cannot be stopped. Click "Show details" to see the list of unstoppable jobs.'), |
| 327 |
det_msg=names, |
| 328 |
show=True, |
| 329 |
) |
| 330 |
jobs = [j for j in jobs if getattr(j, 'killable', True)] |
| 331 |
jobs = [j for j in jobs if j.duration is None] |
| 332 |
for j in jobs: |
| 333 |
self._kill_job(j) |
| 334 |
|
| 335 |
def kill_all_jobs(self): |
| 336 |
for job in self.jobs: |
| 337 |
if isinstance(job, DeviceJob) or job.duration is not None or not getattr(job, 'killable', True): |
| 338 |
continue |
| 339 |
self._kill_job(job) |
| 340 |
|
| 341 |
def terminate_all_jobs(self): |
| 342 |
self.server.killall() |
| 343 |
for job in self.jobs: |
| 344 |
if isinstance(job, DeviceJob) or job.duration is not None or not getattr(job, 'killable', True): |
| 345 |
continue |
| 346 |
if not isinstance(job, ParallelJob): |
| 347 |
self._kill_job(job) |
| 348 |
|
| 349 |
def universal_set(self): |
| 350 |
return {i for i, j in enumerate(self.jobs) if not getattr(j, 'hidden_in_gui', False)} |
| 351 |
|
| 352 |
def get_matches(self, location, query, candidates=None): |
| 353 |
if candidates is None: |
| 354 |
candidates = self.universal_set() |
| 355 |
ans = set() |
| 356 |
if not query: |
| 357 |
return ans |
| 358 |
query = lower(query) |
| 359 |
for j in candidates: |
| 360 |
job = self.jobs[j] |
| 361 |
if job.description and query in lower(job.description): |
| 362 |
ans.add(j) |
| 363 |
return ans |
| 364 |
|
| 365 |
def find(self, query): |
| 366 |
query = query.strip() |
| 367 |
rows = self.parse(query) |
| 368 |
return rows |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
class FilterModel(QSortFilterProxyModel): |
| 375 |
search_done = pyqtSignal(object) |
| 376 |
|
| 377 |
def __init__(self, parent): |
| 378 |
QSortFilterProxyModel.__init__(self, parent) |
| 379 |
self.search_filter = None |
| 380 |
|
| 381 |
def filterAcceptsRow(self, source_row, source_parent): |
| 382 |
if self.search_filter is not None and source_row not in self.search_filter: |
| 383 |
return False |
| 384 |
m = self.sourceModel() |
| 385 |
assert m is not None |
| 386 |
assert isinstance(m, JobManager) |
| 387 |
try: |
| 388 |
job = m.row_to_job(source_row) |
| 389 |
except Exception: |
| 390 |
return False |
| 391 |
return not getattr(job, 'hidden_in_gui', False) |
| 392 |
|
| 393 |
def find(self, query): |
| 394 |
ok = True |
| 395 |
val = None |
| 396 |
if query: |
| 397 |
try: |
| 398 |
sm = self.sourceModel() |
| 399 |
assert sm is not None |
| 400 |
assert isinstance(sm, JobManager) |
| 401 |
val = sm.parse(query) |
| 402 |
except ParseException: |
| 403 |
ok = False |
| 404 |
self.search_filter = val |
| 405 |
self.beginResetModel() |
| 406 |
self.search_done.emit(ok) |
| 407 |
self.endResetModel() |
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
class ProgressBarDelegate(QAbstractItemDelegate): |
| 416 |
def sizeHint(self, option, index): |
| 417 |
return QSize(120, 30) |
| 418 |
|
| 419 |
def paint(self, painter, option, index): |
| 420 |
opts = QStyleOptionProgressBar() |
| 421 |
opts.rect = option.rect |
| 422 |
opts.minimum = 1 |
| 423 |
opts.maximum = 100 |
| 424 |
opts.textVisible = True |
| 425 |
try: |
| 426 |
percent = int(index.model().data(index, Qt.ItemDataRole.DisplayRole)) |
| 427 |
except TypeError, ValueError: |
| 428 |
percent = 0 |
| 429 |
opts.progress = percent |
| 430 |
opts.text = _('Unavailable') if percent == 0 else f'{percent}%' |
| 431 |
app_style = QApplication.style() |
| 432 |
assert app_style is not None |
| 433 |
app_style.drawControl(QStyle.ControlElement.CE_ProgressBar, opts, painter) |
| 434 |
|
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
class DetailView(Dialog): |
| 440 |
def __init__(self, parent, job): |
| 441 |
self.job = job |
| 442 |
self.html_view = hasattr(job, 'html_details') and not getattr(job, 'ignore_html_details', False) |
| 443 |
Dialog.__init__(self, job.description, 'job-detail-view-dialog', parent) |
| 444 |
|
| 445 |
def sizeHint(self): |
| 446 |
return QSize(700, 500) |
| 447 |
|
| 448 |
@property |
| 449 |
def plain_text(self): |
| 450 |
if self.html_view: |
| 451 |
return self.tb.toPlainText() |
| 452 |
return self.log.toPlainText() |
| 453 |
|
| 454 |
def copy_to_clipboard(self): |
| 455 |
clipboard = qapplication_or_fail().clipboard() |
| 456 |
assert clipboard is not None |
| 457 |
clipboard.setText(self.plain_text) |
| 458 |
|
| 459 |
def setup_ui(self): |
| 460 |
self.l = l = QVBoxLayout(self) |
| 461 |
if self.html_view: |
| 462 |
self.tb = w = QTextBrowser(self) |
| 463 |
else: |
| 464 |
self.log = w = QPlainTextEdit(self) |
| 465 |
w.setReadOnly(True), w.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap) |
| 466 |
l.addWidget(w) |
| 467 |
l.addWidget(self.bb) |
| 468 |
self.bb.clear(), self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close) |
| 469 |
self.copy_button = b = self.bb.addButton(_('&Copy to clipboard'), QDialogButtonBox.ButtonRole.ActionRole) |
| 470 |
assert b is not None |
| 471 |
b.setIcon(QIcon.ic('edit-copy.png')) |
| 472 |
b.clicked.connect(self.copy_to_clipboard) |
| 473 |
self.next_pos = 0 |
| 474 |
self.update() |
| 475 |
self.timer = QTimer(self) |
| 476 |
self.timer.timeout.connect(self.update) |
| 477 |
self.timer.start(1000) |
| 478 |
if not self.html_view: |
| 479 |
v = self.log.verticalScrollBar() |
| 480 |
assert v is not None |
| 481 |
v.setValue(v.maximum()) |
| 482 |
|
| 483 |
def update(self, *args, **kwargs): |
| 484 |
if self.html_view: |
| 485 |
html = self.job.html_details |
| 486 |
if len(html) > self.next_pos: |
| 487 |
self.next_pos = len(html) |
| 488 |
self.tb.setHtml(f'<pre style="font-family:monospace">{html}</pre>') |
| 489 |
else: |
| 490 |
f = self.job.log_file |
| 491 |
f.seek(self.next_pos) |
| 492 |
more = f.read() |
| 493 |
self.next_pos = f.tell() |
| 494 |
if more: |
| 495 |
v = self.log.verticalScrollBar() |
| 496 |
assert v is not None |
| 497 |
atbottom = v.value() >= v.maximum() - 1 |
| 498 |
self.log.appendPlainText(more.decode('utf-8', 'replace')) |
| 499 |
if atbottom: |
| 500 |
v.setValue(v.maximum()) |
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
class JobsButton(QWidget): |
| 507 |
tray_tooltip_updated = pyqtSignal(object) |
| 508 |
|
| 509 |
def __init__(self, parent=None): |
| 510 |
QWidget.__init__(self, parent) |
| 511 |
self.num_jobs = 0 |
| 512 |
self.mouse_over = False |
| 513 |
widget_style = self.style() |
| 514 |
assert widget_style is not None |
| 515 |
self.pi = ProgressIndicator(self, widget_style.pixelMetric(QStyle.PixelMetric.PM_ToolBarIconSize)) |
| 516 |
self.pi.setVisible(False) |
| 517 |
self._jobs = QLabel('') |
| 518 |
setattr(self._jobs, 'mouseReleaseEvent', self.mouseReleaseEvent) |
| 519 |
self.update_label() |
| 520 |
self.shortcut = 'Alt+Shift+J' |
| 521 |
|
| 522 |
self.l = l = QHBoxLayout(self) |
| 523 |
l.setSpacing(3) |
| 524 |
l.addWidget(self.pi) |
| 525 |
l.addWidget(self._jobs) |
| 526 |
m = widget_style.pixelMetric(QStyle.PixelMetric.PM_DefaultFrameWidth) |
| 527 |
btn_layout = self.layout() |
| 528 |
assert btn_layout is not None |
| 529 |
btn_layout.setContentsMargins(m, m, m, m) |
| 530 |
self._jobs.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Minimum) |
| 531 |
self.setCursor(Qt.CursorShape.PointingHandCursor) |
| 532 |
b = _('Click to see list of jobs') |
| 533 |
self.action_toggle = QAction(b, parent) |
| 534 |
assert parent is not None |
| 535 |
parent.addAction(self.action_toggle) |
| 536 |
self.action_toggle.triggered.connect(self.toggle) |
| 537 |
self.action_toggle.changed.connect(self.update_tooltip) |
| 538 |
if hasattr(parent, 'keyboard'): |
| 539 |
parent.keyboard.register_shortcut( |
| 540 |
'toggle jobs list', |
| 541 |
_('Show/hide the Jobs List'), |
| 542 |
default_keys=(self.shortcut,), |
| 543 |
action=self.action_toggle, |
| 544 |
) |
| 545 |
self.update_tooltip() |
| 546 |
|
| 547 |
def update_tooltip(self): |
| 548 |
sc = ', '.join(sc.toString(QKeySequence.SequenceFormat.NativeText) for sc in self.action_toggle.shortcuts()) |
| 549 |
self.shortcut = sc or '' |
| 550 |
self.setToolTip(_('Click to see list of jobs [{}]').format(self.shortcut)) |
| 551 |
|
| 552 |
def update_label(self): |
| 553 |
n = self.jobs() |
| 554 |
prefix = '<b>' if n > 0 else '' |
| 555 |
self._jobs.setText(prefix + ' ' + _('Jobs:') + f' {n} ') |
| 556 |
|
| 557 |
def event(self, a0): |
| 558 |
m = None |
| 559 |
et = a0.type() |
| 560 |
if et == QEvent.Type.Enter: |
| 561 |
m = True |
| 562 |
elif et == QEvent.Type.Leave: |
| 563 |
m = False |
| 564 |
if m is not None and m != self.mouse_over: |
| 565 |
self.mouse_over = m |
| 566 |
self.update() |
| 567 |
return QWidget.event(self, a0) |
| 568 |
|
| 569 |
def initialize(self, jobs_dialog, job_manager): |
| 570 |
self.jobs_dialog = jobs_dialog |
| 571 |
job_manager.job_added.connect(self.job_added) |
| 572 |
job_manager.job_done.connect(self.job_done) |
| 573 |
self.jobs_dialog.addAction(self.action_toggle) |
| 574 |
|
| 575 |
def mouseReleaseEvent(self, a0): |
| 576 |
self.toggle() |
| 577 |
|
| 578 |
def toggle(self, *args): |
| 579 |
if self.jobs_dialog.isVisible(): |
| 580 |
self.jobs_dialog.hide() |
| 581 |
else: |
| 582 |
self.jobs_dialog.show() |
| 583 |
|
| 584 |
@property |
| 585 |
def is_running(self): |
| 586 |
return self.pi.isAnimated() |
| 587 |
|
| 588 |
def start(self): |
| 589 |
self.pi.startAnimation() |
| 590 |
self.pi.setVisible(True) |
| 591 |
|
| 592 |
def stop(self): |
| 593 |
self.pi.stopAnimation() |
| 594 |
self.pi.setVisible(False) |
| 595 |
|
| 596 |
def jobs(self): |
| 597 |
return self.num_jobs |
| 598 |
|
| 599 |
def tray_tooltip(self, num=0): |
| 600 |
if num == 0: |
| 601 |
text = _('No running jobs') |
| 602 |
elif num == 1: |
| 603 |
text = _('One running job') |
| 604 |
else: |
| 605 |
text = _('%d running jobs') % num |
| 606 |
if not (islinux or isbsd): |
| 607 |
text = 'calibre: ' + text |
| 608 |
return text |
| 609 |
|
| 610 |
def job_added(self, nnum): |
| 611 |
self.num_jobs = nnum |
| 612 |
self.update_label() |
| 613 |
self.start() |
| 614 |
self.tray_tooltip_updated.emit(self.tray_tooltip(nnum)) |
| 615 |
|
| 616 |
def job_done(self, nnum): |
| 617 |
self.num_jobs = nnum |
| 618 |
self.update_label() |
| 619 |
if nnum == 0: |
| 620 |
self.no_more_jobs() |
| 621 |
self.tray_tooltip_updated.emit(self.tray_tooltip(nnum)) |
| 622 |
|
| 623 |
def no_more_jobs(self): |
| 624 |
if self.is_running: |
| 625 |
self.stop() |
| 626 |
app = QCoreApplication.instance() |
| 627 |
assert app is not None |
| 628 |
assert isinstance(app, QApplication) |
| 629 |
app.alert(self, 5000) |
| 630 |
|
| 631 |
def paintEvent(self, a0): |
| 632 |
if self.mouse_over: |
| 633 |
p = QStylePainter(self) |
| 634 |
tool = QStyleOption() |
| 635 |
tool.initFrom(self) |
| 636 |
tool.rect = self.rect() |
| 637 |
tool.state = QStyle.StateFlag.State_Raised | QStyle.StateFlag.State_Active | QStyle.StateFlag.State_MouseOver |
| 638 |
p.drawPrimitive(QStyle.PrimitiveElement.PE_PanelButtonTool, tool) |
| 639 |
p.end() |
| 640 |
QWidget.paintEvent(self, a0) |
| 641 |
|
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
class JobsDialog(QDialog, Ui_JobsDialog): |
| 647 |
def __init__(self, window, model): |
| 648 |
QDialog.__init__(self, window) |
| 649 |
Ui_JobsDialog.__init__(self) |
| 650 |
self.setupUi(self) |
| 651 |
self.model = model |
| 652 |
self.proxy_model = FilterModel(self) |
| 653 |
self.proxy_model.setSourceModel(self.model) |
| 654 |
self.proxy_model.search_done.connect(self.search.search_done) |
| 655 |
self.jobs_view.setModel(self.proxy_model) |
| 656 |
self.setWindowModality(Qt.WindowModality.NonModal) |
| 657 |
self.setWindowTitle(__appname__ + _(' - Jobs')) |
| 658 |
self.details_button.clicked.connect(self.show_details) |
| 659 |
self.kill_button.clicked.connect(self.kill_job) |
| 660 |
self.stop_all_jobs_button.clicked.connect(self.kill_all_jobs) |
| 661 |
self.pb_delegate = ProgressBarDelegate(self) |
| 662 |
self.jobs_view.setItemDelegateForColumn(2, self.pb_delegate) |
| 663 |
self.jobs_view.doubleClicked.connect(self.show_job_details) |
| 664 |
h_header = self.jobs_view.horizontalHeader() |
| 665 |
assert h_header is not None |
| 666 |
h_header.setSectionsMovable(True) |
| 667 |
self.hide_button.clicked.connect(self.hide_selected) |
| 668 |
self.hide_all_button.clicked.connect(self.hide_all) |
| 669 |
self.show_button.clicked.connect(self.show_hidden) |
| 670 |
self.search.initialize('jobs_search_history', help_text=_('Search for a job by name')) |
| 671 |
self.search.search.connect(self.find) |
| 672 |
connect_lambda(self.search_button.clicked, self, lambda self: self.find(self.search.current_text)) |
| 673 |
self.restore_state() |
| 674 |
|
| 675 |
def restore_state(self): |
| 676 |
try: |
| 677 |
self.restore_geometry(gprefs, 'jobs_dialog_geometry') |
| 678 |
state = gprefs.get('jobs view column layout3', None) |
| 679 |
if state is not None: |
| 680 |
restore_header = self.jobs_view.horizontalHeader() |
| 681 |
assert restore_header is not None |
| 682 |
restore_header.restoreState(QByteArray(state)) |
| 683 |
except Exception: |
| 684 |
import traceback |
| 685 |
|
| 686 |
traceback.print_exc() |
| 687 |
jobs_view_model = self.jobs_view.model() |
| 688 |
assert jobs_view_model is not None |
| 689 |
idx = jobs_view_model.index(0, 0) |
| 690 |
if idx.isValid(): |
| 691 |
sm = self.jobs_view.selectionModel() |
| 692 |
assert sm is not None |
| 693 |
sm.select(idx, QItemSelectionModel.SelectionFlag.ClearAndSelect | QItemSelectionModel.SelectionFlag.Rows) |
| 694 |
|
| 695 |
def save_state(self): |
| 696 |
try: |
| 697 |
with gprefs: |
| 698 |
save_header = self.jobs_view.horizontalHeader() |
| 699 |
assert save_header is not None |
| 700 |
state = bytearray(save_header.saveState()) |
| 701 |
gprefs['jobs view column layout3'] = state |
| 702 |
self.save_geometry(gprefs, 'jobs_dialog_geometry') |
| 703 |
except Exception: |
| 704 |
import traceback |
| 705 |
|
| 706 |
traceback.print_exc() |
| 707 |
|
| 708 |
def show_job_details(self, index): |
| 709 |
index = self.proxy_model.mapToSource(index) |
| 710 |
if index.isValid(): |
| 711 |
row = index.row() |
| 712 |
job = self.model.row_to_job(row) |
| 713 |
d = DetailView(self, job) |
| 714 |
d.exec() |
| 715 |
d.timer.stop() |
| 716 |
|
| 717 |
def show_details(self, *args): |
| 718 |
self.jobs_view.setFocus() |
| 719 |
index = self.jobs_view.currentIndex() |
| 720 |
if index.isValid(): |
| 721 |
self.show_job_details(index) |
| 722 |
|
| 723 |
def kill_job(self, *args): |
| 724 |
kill_sel_model = self.jobs_view.selectionModel() |
| 725 |
assert kill_sel_model is not None |
| 726 |
indices = [self.proxy_model.mapToSource(index) for index in kill_sel_model.selectedRows()] |
| 727 |
indices = [i for i in indices if i.isValid()] |
| 728 |
jobs = self.model.rows_to_jobs([index.row() for index in indices]) |
| 729 |
if not jobs: |
| 730 |
return error_dialog(self, _('No job'), _('No job selected'), show=True) |
| 731 |
if question_dialog( |
| 732 |
self, |
| 733 |
_('Are you sure?'), |
| 734 |
ngettext( |
| 735 |
'Do you really want to stop the selected job?', |
| 736 |
'Do you really want to stop all the selected jobs?', |
| 737 |
len(jobs), |
| 738 |
), |
| 739 |
): |
| 740 |
if len(jobs) > 1: |
| 741 |
self.model.kill_multiple_jobs(jobs, self) |
| 742 |
else: |
| 743 |
self.model.kill_job(jobs[0], self) |
| 744 |
|
| 745 |
def kill_all_jobs(self, *args): |
| 746 |
if question_dialog(self, _('Are you sure?'), _('Do you really want to stop all non-device jobs?')): |
| 747 |
self.model.kill_all_jobs() |
| 748 |
|
| 749 |
def hide_selected(self, *args): |
| 750 |
hide_sel_model = self.jobs_view.selectionModel() |
| 751 |
assert hide_sel_model is not None |
| 752 |
indices = [self.proxy_model.mapToSource(index) for index in hide_sel_model.selectedRows()] |
| 753 |
indices = [i for i in indices if i.isValid()] |
| 754 |
rows = [index.row() for index in indices] |
| 755 |
if not rows: |
| 756 |
return error_dialog(self, _('No job'), _('No job selected'), show=True) |
| 757 |
self.model.hide_jobs(rows) |
| 758 |
self.proxy_model.beginResetModel(), self.proxy_model.endResetModel() |
| 759 |
|
| 760 |
def hide_all(self, *args): |
| 761 |
self.model.hide_jobs(list(range(self.model.rowCount(QModelIndex())))) |
| 762 |
self.proxy_model.beginResetModel(), self.proxy_model.endResetModel() |
| 763 |
|
| 764 |
def show_hidden(self, *args): |
| 765 |
self.model.show_hidden_jobs() |
| 766 |
self.find(self.search.current_text) |
| 767 |
|
| 768 |
def closeEvent(self, a0): |
| 769 |
self.save_state() |
| 770 |
return QDialog.closeEvent(self, a0) |
| 771 |
|
| 772 |
def show(self, *args): |
| 773 |
self.restore_state() |
| 774 |
return QDialog.show(self, *args) |
| 775 |
|
| 776 |
def hide(self, *args): |
| 777 |
self.save_state() |
| 778 |
return QDialog.hide(self, *args) |
| 779 |
|
| 780 |
def reject(self): |
| 781 |
self.save_state() |
| 782 |
QDialog.reject(self) |
| 783 |
|
| 784 |
def find(self, a0): |
| 785 |
self.proxy_model.find(a0) |
| 786 |
|
| 787 |
|
| 788 |
|