summaryrefslogtreecommitdiff
path: root/ui5/filetable.py
blob: 8a13f95422133bb0cd641512444838dad2c726a2 (plain)
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
# -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2015 HP Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Authors: Don Welch
#


# Std Lib
import sys
import os.path
import os
import subprocess

# Local
from base.g import *
from base import utils, magic
from prnt import cups
from base.codes import *
from .ui_utils import *
from base.sixext import to_unicode, to_string_utf8, from_unicode_to_str
# Qt
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# Other UI
from .mimetypesdialog import MimeTypesDialog


FILETABLE_TYPE_PRINT = 0
FILETABLE_TYPE_FAX = 1



class FileTable(QWidget):

    fileListChanged = pyqtSignal()
    isEmpty = pyqtSignal()
    isNotEmpt = pyqtSignal()

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.parent = parent

        self.initUi()
        self.file_list = []
        self.typ = FILETABLE_TYPE_PRINT
        self.selected_filename = None
        self.fax_add_callback = None
        self.allowable_mime_types = cups.getAllowableMIMETypes()

        self.user_settings = UserSettings()
        self.user_settings.load()
        self.user_settings.debug()

        self.working_dir = self.user_settings.working_dir #user_conf.workingDirectory()



    def initUi(self):
        self.gridlayout = QGridLayout(self)
        self.gridlayout.setObjectName("gridlayout")
        self.FileTable = QTableWidget(self)
        self.FileTable.setObjectName("FileTable")
        self.gridlayout.addWidget(self.FileTable,0,0,1,6)
        self.AddFileButton = QPushButton(self)
        self.AddFileButton.setObjectName("AddFileButton")
        self.gridlayout.addWidget(self.AddFileButton,1,0,1,1)
        self.RemoveFileButton = QPushButton(self)
        self.RemoveFileButton.setObjectName("RemoveFileButton")
        self.gridlayout.addWidget(self.RemoveFileButton,1,1,1,1)
        self.MoveFileUpButton = QPushButton(self)
        self.MoveFileUpButton.setObjectName("MoveFileUpButton")
        self.gridlayout.addWidget(self.MoveFileUpButton,1,2,1,1)
        self.MoveFileDownButton = QPushButton(self)
        self.MoveFileDownButton.setObjectName("MoveFileDownButton")
        self.gridlayout.addWidget(self.MoveFileDownButton,1,3,1,1)
        spacerItem = QSpacerItem(91,20,QSizePolicy.Expanding,QSizePolicy.Minimum)
        self.gridlayout.addItem(spacerItem,1,4,1,1)
        self.ShowTypesButton = QPushButton(self)
        self.ShowTypesButton.setObjectName("ShowTypesButton")
        self.gridlayout.addWidget(self.ShowTypesButton,1,5,1,1)
        self.AddFileButton.setText(self.__tr("Add..."))
        self.AddFileButton.setIcon(QIcon(load_pixmap('list_add', '16x16')))
        self.AddFileButton.clicked.connect(self.AddFileButton_clicked)
        self.RemoveFileButton.setIcon(QIcon(load_pixmap('list_remove', '16x16')))
        self.RemoveFileButton.setText(self.__tr("Remove"))
        self.RemoveFileButton.clicked.connect(self.RemoveFileButton_clicked)
        self.MoveFileUpButton.setText(self.__tr("Move Up"))
        self.MoveFileUpButton.setIcon(QIcon(load_pixmap('up', '16x16')))
        self.MoveFileUpButton.clicked.connect(self.MoveFileUpButton_clicked)
        self.MoveFileDownButton.setText(self.__tr("Move Down"))
        self.MoveFileDownButton.setIcon(QIcon(load_pixmap('down', '16x16')))
        self.MoveFileDownButton.clicked.connect(self.MoveFileDownButton_clicked)
        self.ShowTypesButton.setText(self.__tr("Show Valid Types..."))
        self.ShowTypesButton.setIcon(QIcon(load_pixmap('mimetypes', '16x16')))
        self.ShowTypesButton.clicked.connect(self.ShowTypesButton_clicked)
        self.FileTable.setContextMenuPolicy(Qt.CustomContextMenu)
        #self.connect(self.FileTable, SIGNAL("customContextMenuRequested(const QPoint &)"),
        #    self.FileTable_customContextMenuRequested)
        self.FileTable.customContextMenuRequested["const QPoint &"].connect(self.FileTable_customContextMenuRequested)
        self.headers = [self.__tr("Name"), self.__tr("Type"), self.__tr("Folder/Path")]

        self.FileTable.setSortingEnabled(False)
        self.FileTable.itemSelectionChanged.connect(self.FileTable_itemSelectionChanged)


    def setWorkingDir(self, d):
        if os.path.exists(d):
            self.working_dir = d


    def getWorkingDir(self):
        if self.file_list:
            self.working_dir = os.path.pathname(self.file_list[0][0])
            #user_conf.setWorkingDirectory(self.working_dir)
            self.user_settings.working_dir = self.working_dir
            self.user_settings.save()

        return self.working_dir


    def setType(self, t):
        self.typ = t
        if self.typ == FILETABLE_TYPE_FAX:
            self.headers = [self.__tr("Name"), self.__tr("Type"), self.__tr("Pages")]
            if log.is_debug():
                self.headers.append(self.__tr("File"))


    def setFaxCallback(self, callback):
        self.fax_add_callback = callback


    def isNotEmpty(self):
        return len(self.file_list)


    def FileTable_itemSelectionChanged(self):
        self.selected_filename = self.currentFilename()
        self.setUpDownButtons()


    def updateUi(self, show_add_file_if_empty=True):
        self.FileTable.clear()
        self.FileTable.setRowCount(len(self.file_list))
        self.FileTable.setColumnCount(0)

        if self.file_list:
            # self.emit(SIGNAL("isNotEmpty"))
            self.isNotEmpt.emit()
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            try:
                selected = None
                self.FileTable.setColumnCount(len(self.headers))
                self.FileTable.setHorizontalHeaderLabels(self.headers)
                flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

                for row, f in enumerate(self.file_list):
                    filename, mime_type, mime_type_desc, title, num_pages = f
                    col = 0

                    if self.typ == FILETABLE_TYPE_FAX:
                        if title:
                            i = QTableWidgetItem(title)
                        else:
                            i = QTableWidgetItem(os.path.basename(filename))
                    else: # FILETABLE_TYPE_PRINT
                        # Filename (basename)
                        i = QTableWidgetItem(os.path.basename(filename))

                    i.setData(Qt.UserRole, to_unicode(filename))
                    i.setFlags(flags)

                    if self.selected_filename is not None and \
                        self.selected_filename == filename:
                        selected = i

                    self.FileTable.setItem(row, col, i)
                    col += 1

                    # MIME type
                    i = QTableWidgetItem(mime_type_desc)
                    i.setFlags(flags)
                    self.FileTable.setItem(row, col, i)
                    col += 1

                    if self.typ == FILETABLE_TYPE_PRINT:
                        # path/folder
                        i = QTableWidgetItem(os.path.dirname(filename))
                        i.setFlags(flags)
                        self.FileTable.setItem(row, col, i)
                        col += 1

                    if self.typ == FILETABLE_TYPE_FAX:
                        # num pages
                        if num_pages < 1:
                            i = QTableWidgetItem(self.__tr("(unknown)"))
                        else:
                            i = QTableWidgetItem(to_unicode(num_pages))
                        i.setFlags(flags)
                        self.FileTable.setItem(row, col, i)
                        col += 1

                        if self.typ == FILETABLE_TYPE_FAX and log.is_debug():
                            i = QTableWidgetItem(filename)
                            i.setFlags(flags)
                            self.FileTable.setItem(row, col, i)


                self.FileTable.resizeColumnsToContents()

                if selected is None:
                    selected = self.FileTable.item(0, 0)

                selected.setSelected(True)
                self.FileTable.setCurrentItem(selected)

            finally:
                QApplication.restoreOverrideCursor()

            self.RemoveFileButton.setEnabled(True)
            self.RemoveFileButton.setIcon(QIcon(load_pixmap('list_remove', '16x16')))

            self.setUpDownButtons()

        else:
            # self.emit(SIGNAL("isEmpty"))
            self.isEmpty.emit()
            self.RemoveFileButton.setEnabled(False)
            self.setUpDownButtons()

            if show_add_file_if_empty:
                # self.AddFileButton.emit(SIGNAL("clicked()"))
                self.AddFileButton.clicked.emit()


    def setUpDownButtons(self):
        if self.file_list:
            i = self.FileTable.currentRow()

            if len(self.file_list) > 1 and i != len(self.file_list)-1:
                self.MoveFileDownButton.setEnabled(True)
            else:
                self.MoveFileDownButton.setEnabled(False)

            if len(self.file_list) > 1 and i != 0:
                self.MoveFileUpButton.setEnabled(True)
            else:
                self.MoveFileUpButton.setEnabled(False)

        else:
            self.MoveFileDownButton.setEnabled(False)
            self.MoveFileUpButton.setEnabled(False)


    def AddFileButton_clicked(self):
        if self.typ == FILETABLE_TYPE_PRINT:
            s = self.__tr("Select File(s) to Print")
        else:
            stat = ''
            try :
                p = subprocess.Popen('getenforce', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                stat, err = p.communicate()
                stat = to_string_utf8(stat)
            except OSError :
                pass
            except :
                log.exception()
            # if stat.strip('\n') == 'Enforcing' :
            #     FailureUI(self, self.__tr("<b>Unable to add file. Please disable SeLinux.</b><p>Either disable it manually or run hp-doctor from terminal.</p>"),
            #         self.__tr("HP Device Manager"))
            #     return

            s = self.__tr("Select File(s) to Send")

        files = QFileDialog.getOpenFileNames(self, s, self.working_dir, self.__tr("All files (*)"))

        files = [to_unicode(f) for f in files[0]]
        # log.error(files)
        if files:
            self.addFileList(files)

            if self.typ == FILETABLE_TYPE_PRINT:
                self.updateUi(False)


    def addFileList(self, file_list):
        for f in file_list:
            self.addFileFromUI(f)


    def addFileFromUI(self, f, title='', num_pages=0):
        f = os.path.abspath(os.path.expanduser(f))
        log.debug("Trying to add file: %s" % f)
        if os.path.exists(f) and os.access(f, os.R_OK):
            mime_type = magic.mime_type(f)
            mime_type_desc = mime_type
            log.debug("File type of file %s: %s" % (f, mime_type))
            try:
                mime_type_desc = MIME_TYPES_DESC[mime_type][0]
            except KeyError:
                if self.typ == FILETABLE_TYPE_PRINT:
                    FailureUI(self, self.__tr("<b>You are trying to add a file '%s' that cannot be directly printed with this utility.</b><p>To print this file, use the print command in the application that created it.<p>Note: Click <i>Show Valid Types...</i> to view a list of compatible file types that can be directly printed from this utility."%f),
                        self.__tr("HP Device Manager"))
                else:
                    FailureUI(self, self.__tr("<b>You are trying to add a file '%s' that cannot be directly faxed with this utility.</b><p>To fax this file, use the print command in the application that created it (using the appropriate fax print queue).<p>Note: Click <i>Show Valid Types...</i> to view a list of compatible file types that can be directly added to the fax file list in this utility."%f),
                        self.__tr("HP Device Manager"))
            else:
                if self.typ == FILETABLE_TYPE_PRINT:
                    self.addFile(f, mime_type, mime_type_desc, title, num_pages)
                else:
                    self.fax_add_callback(f)
        else:
            FailureUI(self, self.__tr("<b>Unable to add file '%s' to file list (file not found or insufficient permissions).</b><p>Check the file name and try again."%f),
                      self.__tr("HP Device Manager"))


    def addFile(self, f, mime_type, mime_type_desc, title, num_pages):
        log.debug("Adding file %s (%s,%s,%s,%d)" % (f, mime_type, mime_type_desc, title, num_pages))
        self.file_list.append((f, mime_type, mime_type_desc, title, num_pages))
        self.updateUi()
        # self.emit(SIGNAL("fileListChanged"))
        self.fileListChanged.emit()


    def currentFilename(self):
        i = self.FileTable.item(self.FileTable.currentRow(), 0)
        if i is None:
            return None

        return value_str(i.data(Qt.UserRole))


    def RemoveFileButton_clicked(self):
        filename = self.currentFilename()
        if filename is None:
            return

        return self.removeFile(filename)


    def removeFile(self, filename):
        temp = self.file_list[:]
        index = 0
        for f, mime_type, mime_type_desc, title, num_pages in temp:
            if f == to_unicode(filename):
                del self.file_list[index]
                # self.emit(SIGNAL("fileListChanged"))
                self.fileListChanged.emit()
                self.updateUi(False)
                break
            index += 1


    def removeFileByMIMEType(self, mime_type):
        temp = self.file_list[:]
        index = 0
        for filename, m, mime_type_desc, title, num_pages in temp:
            if m == mime_type:
                del self.file_list[index]
                # self.emit(SIGNAL("fileListChanged"))
                self.fileListChanged.emit()
                self.updateUi(False)
                break
            index += 1


    def isMIMETypeInList(self, mime_type):
        for filename, m, mime_type_desc, title, num_pages in self.file_list:
            if m == mime_type:
                return True

        return False


    def ShowTypesButton_clicked(self):
        x = {}
        for a in self.allowable_mime_types:
            x[a] = MIME_TYPES_DESC.get(a, ('Unknown', 'n/a'))

        dlg = MimeTypesDialog(x, self)
        dlg.exec_()


    def MoveFileUpButton_clicked(self):
        filename = self.currentFilename()
        if filename is None:
            return

        utils.list_move_up(self.file_list, filename, self.__compareFilenames)
        self.updateUi()


    def MoveFileDownButton_clicked(self):
        filename = self.currentFilename()
        if filename is None:
            return

        utils.list_move_down(self.file_list, filename, self.__compareFilenames)
        self.updateUi()


    def __compareFilenames(self, a, b):
        return a[0] == b


    def FileTable_customContextMenuRequested(self, p):
        print(p)


    def __tr(self,s,c = None):
        return qApp.translate("FileTable",s,c)