def test_recent_files_register_new_file_success(): recent_files = RecentFiles(10) opened_file = File("file1.txt", "This is file one") recent_files.register_file(opened_file) assert recent_files.load == 1 assert recent_files.searchForFileByPath( opened_file.path).content == opened_file.content
def test_recent_files_flush(): recent_files = RecentFiles(10) opened_file = File("file1.txt", "This is file 1") opened_file2 = File("file2.txt", "This is file 2") recent_files.register_file(opened_file) recent_files.register_file(opened_file2) recent_files.flush() assert recent_files.load == 0 assert recent_files.searchForFileByPath(opened_file.path) is None assert recent_files.searchForFileByPath(opened_file2.path) is None
def refreshMain(self): """ Refresh the recent files list """ recentfiles = RecentFiles().get() print self._layout.count() for index in range(0, self._layout.count() - 4): recentFileButton = self._layout.itemAt(index + 4).widget() try: if self.isMaemo: recentFileButton.setText( os.path.basename( unicode(recentfiles[index]).encode( 'utf-8')).decode('utf-8')) recentFileButton.setValueText( os.path.abspath( unicode(recentfiles[index]).encode( 'utf-8')).decode('utf-8')) else: recentFileButton.setText( os.path.abspath( unicode(recentfiles[index]).encode( 'utf-8')).decode('utf-8')) except StandardError: recentFileButton.setDisabled(True)
def test_recent_files_block(): recent_files = RecentFiles(10) opened_file = File("file1.txt", "This is file 1") opened_file2 = File("file2.txt", "This is file 2") recent_files.register_file(opened_file) recent_files.block() with pytest.raises(Exception): recent_files.register_file(opened_file2) assert recent_files.load == 1 assert recent_files.searchForFileByPath( opened_file.path).content == opened_file.content assert recent_files.searchForFileByPath(opened_file2.path) is None
def save(self): """Hum ... just save ...""" if self.filename.startswith("Unnamed"): filename = self.parent().parent().parent().saveAsFile() if not (filename == ''): return self.filename = filename self.setWindowTitle(QFileInfo(self.filename).fileName()) exception = None filehandle = None try: #Before FileSave plugin hook for plugin in filter_plugins_by_capability('beforeFileSave', self.enabled_plugins): plugin.do_beforeFileSave(self) filehandle = QFile(self.filename) if not filehandle.open(QIODevice.WriteOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) RecentFiles().append(self.filename) except (IOError, OSError), ioError: exception = ioError
def test_recent_files_register_multiple_files_success(): recent_files = RecentFiles(10) opened_file = File("file1.txt", "This is file 1") opened_file2 = File("file2.txt", "This is file 2") recent_files.register_file(opened_file) recent_files.register_file(opened_file2) assert recent_files.load == 2 assert recent_files.searchForFileByPath( opened_file.path).content == opened_file.content assert recent_files.searchForFileByPath( opened_file2.path).content == opened_file2.content
def test_recent_files_register_over_limit(): recent_files = RecentFiles(3) opened_file = File("file1.txt", "This is file 1") opened_file2 = File("file2.txt", "This is file 2") opened_file3 = File("file3.txt", "This is file 3") opened_file4 = File("file4.txt", "This is file 4") recent_files.register_file(opened_file) recent_files.register_file(opened_file2) recent_files.register_file(opened_file3) recent_files.register_file(opened_file4) assert recent_files.load == 3 # Make sure the oldest file gets removed assert recent_files.searchForFileByPath(opened_file.path) is None assert recent_files.searchForFileByPath( opened_file2.path).content == opened_file2.content assert recent_files.searchForFileByPath( opened_file3.path).content == opened_file3.content assert recent_files.searchForFileByPath( opened_file4.path).content == opened_file4.content
def test_recent_files_register_known_file_success(): recent_files = RecentFiles(10) opened_file = File("file1.txt", "This is file 1") opened_file2 = File("file2.txt", "This is file 2") opened_file3 = File("file1.txt", "This is file 1") recent_files.register_file(opened_file) recent_files.register_file(opened_file2) recent_files.print_list() recent_files.register_file(opened_file3) assert recent_files.load == 2 assert recent_files.searchForFileByPath( opened_file.path).content == opened_file.content assert recent_files.searchForFileByPath( opened_file2.path).content == opened_file2.content assert recent_files.searchForFileByPath( opened_file3.path).content == opened_file3.content # Make sure the known_file is the first element in the list assert recent_files.head.path == opened_file3.path
def test_recent_files_initialization_forbidden_capacity(): with pytest.raises(ValueError): recent_files = RecentFiles(-1)
def test_recent_files_initialization(): recent_files = RecentFiles(10) assert recent_files.capacity == 10 assert recent_files.load == 0
def initUI(self): self.objectD['QMainWindow'] = self if self.enable_recent_files: self.recent_file_obj = RecentFiles(self.main_window_title_str) self.recent_file_obj.chdir() self.current_filePath = self.recent_file_obj.get_dir() else: self.current_filePath = here self.current_fileName = '' self.current_config_interface = None # Will change to default at bottom of init self.has_changes = False self.inputD = {} # holds inputs to GUI self.add_action( name='Open', connect_function=self.open_file, shortcut='Ctrl+O', status_tip='Open File', icon_path=os.path.join(here,'./images/open.jpg')) self.add_action( name='Save', connect_function=self.save_file, shortcut='Ctrl+S', status_tip='Save File', icon_path=os.path.join(here,'./images/save_v4.jpg')) self.add_action( name='SaveAs', connect_function=self.saveAs_file, shortcut='F12', status_tip='SaveAs File', icon_path=os.path.join(here,'./images/saveas.jpg')) self.add_action( name='Run', connect_function=self.run_calculation, shortcut='F5', status_tip='Run Calculation', icon_path=os.path.join(here,'./images/run.jpg')) self.add_action( name='Launch Excel', connect_function=self.launch_excel, shortcut='F7', status_tip='Launch Excel', icon_path=os.path.join(here,'./images/excel.jpg')) self.add_action( name='Launch Help', connect_function=self.launch_help, shortcut='F1', status_tip='Launch Help', icon_path=os.path.join(here,'./images/help.jpg')) self.add_action( name='About', connect_function=self.about_message, shortcut='Ctrl+A', status_tip='About This Code', icon_path='') self.add_action( name='Print', connect_function=self.print_output, shortcut='Ctrl+P', status_tip='Print Results', icon_path=os.path.join(here,'./images/print.png')) self.add_action( name='Exit', connect_function=self.maybe_exit, shortcut='Ctrl+Q', status_tip='Exit Application', icon_path=os.path.join(here,'./images/exit.jpg')) if self.enable_recent_files: self.recentFileActs = [] for i in range(RecentFiles.MaxRecentFiles): self.recentFileActs.append( QtGui.QAction(self, visible=False, triggered=self.openRecentFile)) self.status_bar = self.statusBar() self.objectD['statusBar'] = self.status_bar # set up menu bar if defined if GenGUI.standard_menuLL: self.gen_menubar = self.menuBar() for irow,row in enumerate(GenGUI.standard_menuLL): menu_header = row[0] for menu_item in row[1:]: header_obj =self.add_menu_item( name=menu_item, menu_header=menu_header) if irow==0 and self.enable_recent_files: self.separatorAct = header_obj.addSeparator() for i in range(RecentFiles.MaxRecentFiles): header_obj.addAction(self.recentFileActs[i]) header_obj.addSeparator() else: self.enable_recent_files = False # can't have recent files in menu if no menu if GenGUI.toolbarL: self.add_toolbar_items( nameL=GenGUI.toolbarL, tool_size=(40,40), min_toolbar_ht=40, toolbar_margin=0 ) # Debug print of default values if DEBUG_LEVEL > 2: for key,val in sorted( self.input_widget_by_nameD.items() ): print '%15s'%key,val[-1] print self.setGeometry(100, 100, 500, 300) self.setMinimumSize(500,300) #self.setWindowTitle('Qt4_GenGUI') self.updateRecentFileActions() self.add_widgets() self.tabWidget.connect(self.tabWidget,SIGNAL("currentChanged(int)"), self.tabWidget,SLOT("tabChangedSlot(int)")) if len(sys.argv) > 1: print 'Opening Data File:',sys.argv[1] fname = sys.argv[1] if not fname.lower().endswith(self.data_file_suffix.lower()): print ' Assuming data suffix: "%s"'%self.data_file_suffix fname = fname + self.data_file_suffix fname = os.path.abspath( fname ) if os.path.isfile( fname ): self.load_file( fname ) print '...NOTICE... loaded file:' print ' ',fname else: print '...ERROR... could not find file:' print ' ',fname self.updateRecentFileActions() self.clear_changes() # No current changes to worry about self.set_main_window_title() self.show()
class GenGUI(GenericGUI): """A generic GUI built with pyQt4. Used as starting point for new GUI apps. """ objectD = {} # later set to self.objectD of GenGUI tabL = [] # used by MyTabWidget to ID tabs tabIndexD = {} # index=tab label, value=tabWidget index tabObjectD = {}# index=tab label, value=QtGui.QWidget() # Placed onto toolbar in order toolbarL = ['Open', 'Save', 'SaveAs', 'Run', 'Launch Excel', 'Launch Help', 'Print', 'Exit'] # First member of each list is menu header. Rest of list are menu items. standard_menuLL = [['File', 'Open', 'Save', 'SaveAs', 'Print', 'Exit'], ['Tools','Run','Launch Excel'], ['Help','Launch Help', 'About']] def __init__(self, centerContent=True, enable_recent_files=True): super(GenGUI, self).__init__(centerContent=centerContent) GenGUI.objectD = self.objectD # make sure objectD from GenericGUI is same as GenGUI self.enable_recent_files = enable_recent_files self.initVars() self.initUI() def initVars(self): self.data_file_suffix = '.inp' GenGUI.tabL.extend( ['Tab 1','Tab 2'] ) self.main_window_title_str = 'Qt4_GenGUI' def add_widgets( self ): self.add_label( advance_n=True, text='Your label Here', name='sample', text_align='', text_font=ARIAL_12B, col=1, width=1) self.add_push_button( name='testBtn', fulldesc='This is a Test', advance_n=False, text_font=ARIAL_12B, col=3, connect_function=self.about_message, background='', pressed_bgrnd='') self.add_radio_btns(['radio 1','radio 2','radio 3'], name='main_radio', init_val=2, advance_n=False, fulldesc='Radio Choices', text_font=ARIAL_10, col=0) self.add_image( advance_n=False, path_to_image=r'D:\py_proj_2016\Qt4_GenGUI\qt4_gengui\images\document.png', name='doc', image_align='', col=2, width=1, height=1) # ==================================================== if GenGUI.tabL: self.tabWidget = MyTabWidget() for tab_label in GenGUI.tabL: tabObj = MyWidget() GenGUI.tabObjectD[tab_label] = tabObj GenGUI.tabIndexD[tab_label] = self.tabWidget.addTab( tabObj ,tab_label) Nrow = self.get_next_row_number( advance_n=True) self.grid.addWidget(self.tabWidget, Nrow, 1, 4, 1) self.set_next_row_number( Nrow + 4 ) tabObj = GenGUI.tabObjectD['Tab 1'] self.add_label( advance_n=True, text='Your label Here', name='sample', text_align='', text_font=ARIAL_12B, col=1, width=1, parent=tabObj) tabObj = GenGUI.tabObjectD['Tab 2'] self.add_radio_btns(['tab 1','tab 2','tab 3'], name='tab_radio', init_val=2, advance_n=False, fulldesc='Tab Choices', text_font=ARIAL_10, col=0, parent=tabObj) self.add_check_box( advance_n=True, text='Choose Good', name='chkbox_sample', text_font=ARIAL_12, col=3, width=1, parent=None, layout=None) # ============================================= #self.add_some_vertical_space() self.add_list_box(['choice 1','choice 2','choice 3'], name='choiceNum', init_val=1, advance_n=True, fulldesc='Generic Choices', connect_function=None, text_font=ARIAL_10, col=0) self.add_some_horizontal_space( col=10, stretch=11) # ================================ self.add_lineEdit( advance_n=False, text_font=ARIAL_10, onChange_function=None, name='myval', fulldesc='Some Value', col=2, width=1) self.add_spin_box( name='Number', n_min=1, n_max=99, init_val=13, advance_n=True, fulldesc='Number of Things', text_align='right', text_font=ARIAL_10, col=0, width=120) # =================================== self.add_combo_box( ['combo 1','combo 2','combo 3'], index_init=0, name='cycle_desc', advance_n=False, fulldesc='Select Combo Item', text_align='right', text_font=ARIAL_10, col=0, width=100) self.add_hbox_lineEdit( advance_n=True, text_font=ARIAL_10, name='mix_rat', fulldesc='Mixture Ratio', col=2, width=1) def initUI(self): self.objectD['QMainWindow'] = self if self.enable_recent_files: self.recent_file_obj = RecentFiles(self.main_window_title_str) self.recent_file_obj.chdir() self.current_filePath = self.recent_file_obj.get_dir() else: self.current_filePath = here self.current_fileName = '' self.current_config_interface = None # Will change to default at bottom of init self.has_changes = False self.inputD = {} # holds inputs to GUI self.add_action( name='Open', connect_function=self.open_file, shortcut='Ctrl+O', status_tip='Open File', icon_path=os.path.join(here,'./images/open.jpg')) self.add_action( name='Save', connect_function=self.save_file, shortcut='Ctrl+S', status_tip='Save File', icon_path=os.path.join(here,'./images/save_v4.jpg')) self.add_action( name='SaveAs', connect_function=self.saveAs_file, shortcut='F12', status_tip='SaveAs File', icon_path=os.path.join(here,'./images/saveas.jpg')) self.add_action( name='Run', connect_function=self.run_calculation, shortcut='F5', status_tip='Run Calculation', icon_path=os.path.join(here,'./images/run.jpg')) self.add_action( name='Launch Excel', connect_function=self.launch_excel, shortcut='F7', status_tip='Launch Excel', icon_path=os.path.join(here,'./images/excel.jpg')) self.add_action( name='Launch Help', connect_function=self.launch_help, shortcut='F1', status_tip='Launch Help', icon_path=os.path.join(here,'./images/help.jpg')) self.add_action( name='About', connect_function=self.about_message, shortcut='Ctrl+A', status_tip='About This Code', icon_path='') self.add_action( name='Print', connect_function=self.print_output, shortcut='Ctrl+P', status_tip='Print Results', icon_path=os.path.join(here,'./images/print.png')) self.add_action( name='Exit', connect_function=self.maybe_exit, shortcut='Ctrl+Q', status_tip='Exit Application', icon_path=os.path.join(here,'./images/exit.jpg')) if self.enable_recent_files: self.recentFileActs = [] for i in range(RecentFiles.MaxRecentFiles): self.recentFileActs.append( QtGui.QAction(self, visible=False, triggered=self.openRecentFile)) self.status_bar = self.statusBar() self.objectD['statusBar'] = self.status_bar # set up menu bar if defined if GenGUI.standard_menuLL: self.gen_menubar = self.menuBar() for irow,row in enumerate(GenGUI.standard_menuLL): menu_header = row[0] for menu_item in row[1:]: header_obj =self.add_menu_item( name=menu_item, menu_header=menu_header) if irow==0 and self.enable_recent_files: self.separatorAct = header_obj.addSeparator() for i in range(RecentFiles.MaxRecentFiles): header_obj.addAction(self.recentFileActs[i]) header_obj.addSeparator() else: self.enable_recent_files = False # can't have recent files in menu if no menu if GenGUI.toolbarL: self.add_toolbar_items( nameL=GenGUI.toolbarL, tool_size=(40,40), min_toolbar_ht=40, toolbar_margin=0 ) # Debug print of default values if DEBUG_LEVEL > 2: for key,val in sorted( self.input_widget_by_nameD.items() ): print '%15s'%key,val[-1] print self.setGeometry(100, 100, 500, 300) self.setMinimumSize(500,300) #self.setWindowTitle('Qt4_GenGUI') self.updateRecentFileActions() self.add_widgets() self.tabWidget.connect(self.tabWidget,SIGNAL("currentChanged(int)"), self.tabWidget,SLOT("tabChangedSlot(int)")) if len(sys.argv) > 1: print 'Opening Data File:',sys.argv[1] fname = sys.argv[1] if not fname.lower().endswith(self.data_file_suffix.lower()): print ' Assuming data suffix: "%s"'%self.data_file_suffix fname = fname + self.data_file_suffix fname = os.path.abspath( fname ) if os.path.isfile( fname ): self.load_file( fname ) print '...NOTICE... loaded file:' print ' ',fname else: print '...ERROR... could not find file:' print ' ',fname self.updateRecentFileActions() self.clear_changes() # No current changes to worry about self.set_main_window_title() self.show() def updateRecentFileActions(self): if not self.has_menu_bar: return if not self.enable_recent_files: return fileL = self.recent_file_obj.recent_fileL numRecentFiles = min(len(fileL), RecentFiles.MaxRecentFiles) for i in range(numRecentFiles): head,tail = os.path.split( fileL[i] ) text = "&%d %s" % (i + 1, tail) self.recentFileActs[i].setText(text) self.recentFileActs[i].setData( fileL[i] ) self.recentFileActs[i].setVisible(True) for j in range(numRecentFiles, RecentFiles.MaxRecentFiles): self.recentFileActs[j].setVisible(False) self.separatorAct.setVisible((numRecentFiles > 0)) def openRecentFile(self): action = self.sender() if action: self.load_file( str(action.data().toString()) ) #print dir( action.data() ) #print action.data().toString() def flag_changes(self): self.has_changes = True if self.current_config_interface is not None: self.current_config_interface.has_changes = True # Has current changes to worry about def clear_changes(self): self.has_changes = False if self.current_config_interface is not None: self.current_config_interface.has_changes = False # No current changes to worry about def set_main_window_title(self): s = self.main_window_title_str if self.current_fileName: s = s + ' (%s)'%self.current_fileName self.setWindowTitle( s ) def set_pending_file_value(self, name, val): self.has_changes = True if self.current_config_interface is not None: self.current_config_interface['Input',name] = val if DEBUG_LEVEL > 2: print 'Set Pending File Value',name,val def continue_after_possible_save(self): """ Return True if there are pending changes to the current inputs AND... the user elects to stop current action and save. """ if self.current_config_interface is None and (not self.has_changes): return True else: if self.has_changes or self.current_config_interface.has_changes: msg = "Do you want to Save First?\n"+\ "\n YES\t\tSave changes and Exit"+\ "\n NO\t\tDiscard change and Exit"+\ "\n CANCEL\tKeep application open" reply = QtGui.QMessageBox.question(self, 'There are pending changes to the input.', msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Yes: self.save_file() return True elif reply == QtGui.QMessageBox.No: return True else: return True return False # Returns False if Cancel is selected def load_file(self, full_fname): if self.enable_recent_files: self.recent_file_obj.update( full_fname ) self.updateRecentFileActions() head,tail = os.path.split( full_fname ) self.current_filePath = head self.current_fileName = tail self.current_config_interface = ConfigInterface( config_filename=full_fname, sectionL=['Input'] ) inputD = self.current_config_interface.get_dictionary() if 'Input' in inputD: self.inputD = inputD['Input'] self.set_IO_values( ) self.status_bar.showMessage( 'Opened File: "%s"'%self.current_fileName ) self.updateRecentFileActions() # No current changes to worry about self.clear_changes() # No current changes to worry about self.set_main_window_title() def closeEvent(self, event): if self.continue_after_possible_save(): event.accept() else: event.ignore() QtGui.QMessageBox.information(self, "Cancelled Exit Command", 'Pending Changes To: "%s"'%self.current_fileName); def maybe_exit(self): if self.continue_after_possible_save(): QtGui.qApp.quit() else: QtGui.QMessageBox.information(self, "Cancelled Exit Command", 'Pending Changes To: "%s"'%self.current_fileName); def open_file(self): if not self.continue_after_possible_save(): QtGui.QMessageBox.information(self, "Cancelled Open Command", 'Pending Changes To: "%s"'%self.current_fileName); return Qfname = QtGui.QFileDialog.getOpenFileName(self, 'Open file',self.current_filePath, 'Qt4_GenGUI (*%s)'%self.data_file_suffix ) if Qfname: self.load_file( str( Qfname ) ) def save_file(self): if self.current_config_interface is not None: if self.enable_recent_files: self.recent_file_obj.update( self.current_config_interface.config_filename ) self.updateRecentFileActions() resultD = self.get_IO_values() keyL = resultD.keys() keyL.sort(key=str.lower) for key in keyL: self.current_config_interface['Input',key] = resultD[key] self.current_config_interface.save_file() self.status_bar.showMessage( 'Saved to File: "%s"'%self.current_fileName ) self.set_main_window_title() QtGui.QMessageBox.information(self, "Saved to File: %s"%self.current_fileName, 'at: "%s"'%self.current_filePath); #self.updateRecentFileActions() # No current changes to worry about self.clear_changes() # No current changes to worry about else: self.saveAs_file() def saveAs_file(self): Qfname = QtGui.QFileDialog.getSaveFileName(self, 'Save file', self.current_filePath, 'Qt4_GenGUI (*%s)'%self.data_file_suffix ) if Qfname: fname = str( Qfname ) head,tail = os.path.split( fname ) if self.enable_recent_files: self.recent_file_obj.update( fname ) self.updateRecentFileActions() self.current_filePath = head self.current_fileName = tail self.current_config_interface = ConfigInterface( config_filename=fname, sectionL=['Input'] ) resultD = self.get_IO_values() keyL = resultD.keys() keyL.sort(key=str.lower) for key in keyL: self.current_config_interface['Input',key] = resultD[key] self.current_config_interface.save_file() self.status_bar.showMessage( 'Saved to File: "%s"'%self.current_fileName ) self.updateRecentFileActions() self.set_main_window_title() # No current changes to worry about self.clear_changes() # No current changes to worry about def launch_excel(self): self.get_IO_values() # loads self.inputD keyL = self.inputD.keys() keyL.sort( key=str.lower ) xl = xlChart.xlChart() xl.xlApp.DisplayAlerts = 0 # Allow Quick Close without Save Message rs = [] for key in keyL: rs.append([key, self.inputD[key]]) xl.makeDataSheet( rs, sheetName='GenGUI', rowFormatL=None) xl.pageSetupForSheet(landscape=0, fitWidth=1, fitHeight=1, marginInches=0.0) png_file = os.path.join(here, 'images', 'document.png') xl.AddPictureToDataSheet(imgAbsPath=png_file, sheetName='GenGUI', left=250, top=50, width=150, height=150) #QtGui.QMessageBox.information(self, # "Need Excel Logic!", # "Run Excel here."); def run_calculation(self): QtGui.QMessageBox.information(self, "Need Calculation Logic!", "Run Calculation here."); def print_output(self): #self.run_calculation() QtGui.QMessageBox.information(self, "Need Print Logic!", "Run Print here."); def about_message(self): #self.run_calculation() QtGui.QMessageBox.information(self, "About Qt4_GenGUI v:%s"%__version__, """This generic GUI creates a main page, menu, toolbar and statusbar. Modify this starting point to suit your projets' needs. author: Charlie Taylor <*****@*****.**> License: OSI Approved GNU General Public License v3 (GPLv3) """); def launch_help(self): webbrowser.open(INDEX_PAGE)