def _addSwitch(self, v, cnt): control = QCheckBox(v.name) control.setChecked(v.value) control.setFocusPolicy(Qt.StrongFocus) f = control.font() f.setPointSizeF(11) control.setFont(f) control.tag = cnt if self.styleName == "mac": control.setAttribute(Qt.WA_MacSmallSize, True) self.layout.addWidget(control, cnt, 1) self.connect(control, SIGNAL("stateChanged(int)"), self.booleanChanged_)
def _addSwitch(self, v, cnt): control = QCheckBox(v.name) control.setChecked(v.value) control.setFocusPolicy(Qt.StrongFocus) f = control.font() f.setPointSizeF(11) control.setFont(f) control.tag = cnt if self.styleName == "mac": control.setAttribute(Qt.WA_MacSmallSize, True) self.layout.addWidget(control, cnt, 1) self.connect(control, SIGNAL("stateChanged(int)"), self.booleanChanged_)
def addRanges(self, keys, extents): for key, extent in zip(keys, extents): w = ValueRangeWidget(self) w.setFocusPolicy(Qt.TabFocus) w.setDType(numpy.uint32) w.setValues(0,extent) w.setLimits(0,extent) #w.setLabels("min:","max:") self.roiWidgets.append(w) row = self.roiLayout.rowCount() align = Qt.Alignment(Qt.AlignLeft) check = QCheckBox() self.roiCheckBoxes.append(check) check.setChecked(True) check.setFocusPolicy(Qt.ClickFocus) if extent == 1: w.setEnabled(False) self.roiLayout.addWidget(QLabel(key + ": "),row, 0, align) self.roiLayout.addWidget(self.roiWidgets[-1],row, 1, align) self.roiLayout.addWidget(check,row, 2, align) def onChanged(i): val1,val2 = self.roiWidgets[i].getValues() lim1,lim2 = self.roiWidgets[i].getLimits() #limits are stored as ranges if val1==lim1 and val2==lim2: self.roiCheckBoxes[i].setChecked(True) else: self.roiCheckBoxes[i].setChecked(False) def onCheck(i, state): if state == 0: return self.roiWidgets[i].setValues(0,extents[i]) self.roiCheckBoxes[i].setChecked(True) for i, check in enumerate(self.roiCheckBoxes): check.stateChanged.connect(partial(onCheck, i)) self.roiWidgets[i].changedSignal.connect(partial(onChanged, i))
def addRanges(self, keys, extents): for key, extent in zip(keys, extents): w = ValueRangeWidget(self) w.setFocusPolicy(Qt.TabFocus) w.setDType(numpy.uint32) w.setValues(0,extent) w.setLimits(0,extent) #w.setLabels("min:","max:") self.roiWidgets.append(w) row = self.roiLayout.rowCount() align = Qt.Alignment(Qt.AlignLeft) check = QCheckBox() self.roiCheckBoxes.append(check) check.setChecked(True) check.setFocusPolicy(Qt.ClickFocus) w.changedSignal.connect(partial(check.setChecked,False)) if extent == 1: w.setEnabled(False) check.toggled.connect(partial(check.setChecked, True)) #w.setBackgroundColor("gray", [0,1]) self.roiLayout.addWidget(QLabel(key + ": "),row, 0, align) self.roiLayout.addWidget(self.roiWidgets[-1],row, 1, align) self.roiLayout.addWidget(check,row, 2, align)
def __init__(self): QMainWindow.__init__(self) self.commSignal.connect(self.plot) self.figure, self.drawing = plt.subplots() self.figure.set_tight_layout(True) self.canvas = FigureCanvas(self.figure) self.setCentralWidget(self.canvas) dock = QDockWidget("Values") self.addDockWidget(Qt.RightDockWidgetArea, dock) # ----------------------------------------------------------------- sliders = QWidget() sliders_grid = QGridLayout(sliders) chkRepeaterRun = QCheckBox("&Repeater...") chkRepeaterRun.setFocusPolicy(Qt.NoFocus) sliders_grid.addWidget(chkRepeaterRun, 0, 0) self.lowROI = QLineEdit() # self.lowROI.setFocusPolicy(Qt.NoFocus) self.lowROI.setValidator(QIntValidator(0, self.maxBins - 1)) self.highROI = QLineEdit() # self.highROI.setFocusPolicy(Qt.NoFocus) self.highROI.setValidator(QIntValidator(0, self.maxBins - 1)) sliders_grid.addWidget(self.lowROI, 1, 0) sliders_grid.addWidget(self.highROI, 2, 0) dock.setWidget(sliders) # ----------------------------------------------------------------- self.dxpMcaPVs = [] self.mcas = [] self.noOfElement = 7 self.dxpAcqPV = epics.PV('BL7D:dxpXMAP:Acquiring') for i in range(1, self.noOfElement+1, 1): self.dxpMcaPVs.append(epics.PV('BL7D:dxpXMAP:mca' + str(i))) # Read current mcas for i in self.dxpMcaPVs: self.mcas.append(i.get()) # Create x axis value self.x = np.arange(0, len(self.mcas[0]), 1) # 1st plot mca data self.drawing.plot(self.x, self.mcas[0], self.x, self.mcas[1], self.x, self.mcas[2], self.x, self.mcas[3], self.x, self.mcas[4], self.x, self.mcas[5], self.x, self.mcas[6], linewidth=1.0) self.drawing.grid() self.drawing.autoscale() self.a = Point(self.canvas, self.drawing, self.maxBins / 4, self.callback) self.b = Point(self.canvas, self.drawing, self.maxBins / 2, self.callback) # self.plot() # We need to draw *and* flush self.figure.canvas.draw() self.figure.canvas.flush_events() self.addCallbackAcq()
class mpl_widget(QWidget): def __init__(self, parent=None, mainWidget=None): self._SELECTEDCELLS = list() # container for instances of selected cells, so we can delete them when we want self._SELECTEDCELLS_IJ = list() # container for coords of selected cells, so we can delete them when we want self._SELECTEDCELLLINES = list() # container for instances of selected cells, so we can delete them when we want self._GRIDLINES = None QWidget.__init__(self, parent) self.mainWidget = mainWidget self.create_main_frame() self.mpl_menu = mpl_menu(self) self.shift_is_held = False #self.connect(self.mpl_menu, QtCore.SIGNAL('mySignal'), self.mySlot) #print 'my parent is:', parent self.clear_selection() self.init_tooltips() def init_tooltips(self): self.canvas.setToolTip('If 2D plot => RMB click toggles menu <br> - RMB click selects cell <br> - selected cells are drawn with black border') self.grid_cb.setToolTip('If 2D plot => show computational grid <br> If 1D plot => show normal gridlines') self.cbar_button.setToolTip('If 2D plot => controls the color range. <br> Note: <br> - pressing UP and DOWN arrows cycles through colormaps <br> - dragging colorbar with RMB scales the color-range <br> - dragging colorbar with LMB shifts the color-range') self.mpl_toolbar.setToolTip('Shows coordinates (i,j, lat,lon) and data-value(z) under the cursor. <br> if you see <i>>>></i> coordinates are not visible. Enlarge the window') def create_main_frame(self): self.fig = Figure(dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.setFocusPolicy( Qt.ClickFocus ) self.canvas.setFocus() self.mpl_toolbar = myNavigationToolbar(self.canvas, self) self.canvas.mpl_connect('button_press_event', self.on_click) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('key_release_event', self.on_key_release) #self.canvas.mpl_connect('button_press_event', self.disable_clicks) self.cbar_button = QPushButton("Color Range") self.cbar_button.setFocusPolicy( Qt.NoFocus ) self.grid_cb = QCheckBox("Show Grid") self.grid_cb.setFocusPolicy( Qt.NoFocus ) self.grid_cb.stateChanged.connect(self.showGrid) vbox = QVBoxLayout() hbox = QHBoxLayout() vbox.addWidget(self.canvas) # the matplotlib canvas hbox.addWidget(self.mpl_toolbar) hbox.addWidget(self.cbar_button) hbox.addWidget(self.grid_cb) vbox.addLayout(hbox) self.setLayout(vbox) def on_click(self, event): if event.inaxes != self.get_axes()[0]: return #if self.get_axes()[0].format_coord(event.x, event.y) == 'outside data area': return if self.allow_menu(): self.allow_popup_menu = True if self.shift_is_held: self.allow_popup_menu = False point = [int(event.xdata + .5), int(event.ydata + .5)] #print '>>>', point, '\t currently {0} selected'.format(len(self._SELECTEDCELLS)) if event.button == 3 : #if RMB is clicked # working with dialog for transect! if self.mainWidget.transect_dlg: if self.mainWidget.transect_dlg.toogle_show_after_selected_cell: realx, realy = self.get_real_xy(event.xdata, event.ydata, self.mainWidget.detect_variable_dimensions()) realpoint = [realy, realx] #print 'real xy:', realpoint if self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 1: # select point 1 self.allow_popup_menu = False self.mainWidget.transect_dlg.data.set_p1(realpoint) elif self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 2: # select point 2 self.allow_popup_menu = False self.mainWidget.transect_dlg.data.set_p2(realpoint) self.mainWidget.transect_dlg.update() self.mainWidget.transect_dlg.show() # working with dialog for flux! if self.mainWidget.flux_dlg: if self.mainWidget.flux_dlg.toogle_show_after_selected_cell: if self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 1: # select point 1 self.allow_popup_menu = False self.mainWidget.flux_dlg.data.set_p1(point) elif self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 2: # select point 2 self.allow_popup_menu = False self.mainWidget.flux_dlg.data.set_p2(point) self.mainWidget.flux_dlg.update() self.mainWidget.flux_dlg.show() if len(self._SELECTEDCELLS) == 0: # if no cell is selected self.add_selected_cell(point) else: # if some cells are already selected if self.mpl_menu.allow_rmb_select_cells() or self.shift_is_held: # check if this point is already selected: already_selected = False for p in self._SELECTEDCELLS_IJ: if (point[0] == p[0]) and (point[1] == p[1]): already_selected = True print 'cell already selected... is not added' if not already_selected: self.add_selected_cell(point) else: pass #self.clear_selection() #self.add_selected_cell(point) def cells_selected(self): if self._SELECTEDCELLS: return len(self._SELECTEDCELLS) else: return False def add_selected_cell(self, point): ''' point = [i, j]''' print 'selected cell:', point[0], point[1] c = self.draw_picked_cell(point) self._SELECTEDCELLS.append(c) self._SELECTEDCELLS_IJ.append(point) def get_selected_cells_ij(self): return self._SELECTEDCELLS_IJ def clear_selection(self): ''' delete all graphical objects of selected cells redraw canvas ''' print 'clearing stuff' if len(self._SELECTEDCELLLINES) > 0: for line in self._SELECTEDCELLLINES: l = line.pop(0) l.remove() del l del self._SELECTEDCELLLINES[:] #print 'cells ---- before:', len(self._SELECTEDCELLS) if len(self._SELECTEDCELLS) > 0: for cell in self._SELECTEDCELLS: for line in cell: l = line.pop(0) l.remove() del l del self._SELECTEDCELLS[:] #print 'cells ---- left:', len(self._SELECTEDCELLS) #print 'cells-coords ----' #print len(self._SELECTEDCELLS_IJ) if self._SELECTEDCELLS_IJ: for cellcoords in self._SELECTEDCELLS_IJ: #cc = cellcoords.pop(0) #cellcoords.remove() del cellcoords del self._SELECTEDCELLS_IJ[:] #print 'cells ---- left,', len(self._SELECTEDCELLS_IJ) if len(self._SELECTEDCELLS) != 0: raise ValueError('List "self._SELECTEDCELLS" was not flushed') if len(self._SELECTEDCELLLINES) != 0: raise ValueError('List "self._SELECTEDCELLLINES" was not flushed') if len(self._SELECTEDCELLS_IJ) != 0: raise ValueError('List "self._SELECTEDCELLLINES" was not flushed') # update plot self.canvas.draw() #print 'finishing clear: cells left', len(self._SELECTEDCELLS) def showGrid(self, state): if self.fig.axes: current_plot = self.mainWidget.get_plotType() current_plot2D = self.mainWidget.get_plotType_for_timeseries() if state == Qt.Checked: if current_plot == '1D' or (current_plot2D =="2DZT"): self.fig.axes[0].grid(True) elif current_plot == '2D' and (not current_plot2D =="2DZT"): self.draw_pixel_grid(True) else: if current_plot == '1D' or (current_plot2D =="2DZT"): self.fig.axes[0].grid(False) elif current_plot == '2D' and (not current_plot2D =="2DZT"): self.draw_pixel_grid(False) self.canvas.draw() def draw_picked_cell(self, point): x = point[0] y = point[1] ''' approach drawing a patch... not working cell_bnd = patches.Rectangle((x-.5, y-.5), 1, 1, fill=False, edgecolor="black", hatch=None, linewidth=1.) cell_instance = self.fig.axes[0].add_patch(cell_bnd) ''' b_line = [(x-.5, x+.5), (y-.5, y-.5)] r_line = [(x+.5, x+.5), (y-.5, y+.5)] t_line = [(x-.5, x+.5), (y+.5, y+.5)] l_line = [(x-.5, x-.5), (y-.5, y+.5)] cell = [b_line, r_line, t_line, l_line] for i, l in enumerate(cell): ll = self.fig.axes[0].plot(l[0], l[1], 'k-', lw=.8) cell[i] = ll # overwriting current Line2D object with object binded to an axes #self._SELECTEDCELLS.append(cell) # collecting reference to this cell to be able to delete it #self._SELECTEDCELLS_IJ.append(point) # collecting reference to this cell to be able to delete it self.canvas.draw() return cell def draw_line(self, point1, point2): line = [(point1[0], point2[0]), (point1[1], point2[1])] l = self.fig.axes[0].plot(line[0], line[1], 'k-', lw=2) return l def draw_pixel_grid(self, enable=True): if enable: dx = 1 dy = 1 x0 = -.5 y0 = -.5 if self.mainWidget.get_plotType_for_timeseries() == '2DXY': nx = self.mainWidget.get_nX() ny = self.mainWidget.get_nY() elif self.mainWidget.get_plotType_for_timeseries() == '2DZY': nx = self.mainWidget.get_nY() ny = self.mainWidget.get_nZ() elif self.mainWidget.get_plotType_for_timeseries() == '2DZX': nx = self.mainWidget.get_nX() ny = self.mainWidget.get_nZ() self._GRIDLINES = list() for n_hline in np.arange(ny+1): hline = [(x0, x0+nx), (y0+n_hline, y0+n_hline)] l = self.fig.axes[0].plot(hline[0], hline[1], 'k-', lw=.2) self._GRIDLINES.append(l) # collecting reference to this line to be able to delete it for n_vline in np.arange(nx+1): vline = [(x0+n_vline, x0+n_vline), (y0, y0+ny)] l = self.fig.axes[0].plot(vline[0], vline[1], 'k-', lw=.2) self._GRIDLINES.append(l) # collecting reference to this line to be able to delete it if not enable: #print 'deleting lines...' if self._GRIDLINES: # if lines were created #print 'lines are here...' for line in self._GRIDLINES: #print line l = line.pop(0) l.remove() del l self.fig.canvas.draw() def on_key_press(self, event): #print 'key pressed:', event.key if event.key == 'shift': self.shift_is_held = True def on_key_release(self, event): #print 'key released:', event.key if event.key == 'shift': self.shift_is_held = False elif event.key == 'escape': self.clear_selection() def change_coordinate_formatter(self, ax, data2d, bruteforce_flag=None, bruteforce_dims=None): ''' see http://stackoverflow.com/questions/14754931/matplotlib-values-under-cursor ''' numrows, numcols = data2d.shape bruteforce_mode_on = False bruteforce_mode_on = (bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2]) def format_coord(x, y): col = int(x+0.5) row = int(y+0.5) if not bruteforce_mode_on: if col >= 0 and col < numcols and row >= 0 and row < numrows: #z = data2d[row, col] # sice we have artificially reversed y-coordinate axes, now reverse data! # numrows-1, because if nrows=10 => row=[0:9] z = data2d[numrows-1-row, col] #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z) return 'i=%d j=%d z=%.6f' % (col, row, z) else: #return 'x=%1.4f, y=%1.4f' % (x, y) return 'outside data area' elif bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2]: ''' our extend in X=[-0.5:numcols-0.5], Y=[-0.5:numrows-0.5], because col,row is cell center! ''' if col >= 0 and col < numcols and row >= 0 and row < numrows: #z = data2d[row, col] # sice we have artificially reversed y-coordinate axes, now reverse data! # numrows-1, because if nrows=10 => row=[0:9] z = data2d[numrows-1-row, col] real_x, real_y = self.get_real_xy(x, y, bruteforce_dims) #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z) #return 'i=%d j=%d z=%.3f x=%.4f y=%.4f' % (col, row, z, real_x, real_y) return 'i=%d j=%d z=%.3f, %s=%.2f %s=%.2f' % ( col, row, z, bruteforce_dims[-1], real_x, bruteforce_dims[-2], real_y) else: #return 'x=%1.4f, y=%1.4f' % (x, y) return 'outside data area' else: raise ValueError('bruteforce_flag can be $None$ or $"2DXY"$. Passed %s' % bruteforce_flag) ax.format_coord = format_coord def allow_menu(self): allow = False #print "self.mainWidget.get_plotType():", self.mainWidget.get_plotType() #print "self.mainWidget.get_plotType_for_timeseries():", self.mainWidget.get_plotType_for_timeseries() if self.mainWidget.get_plotType() == "2D" and not self.mainWidget.get_plotType_for_timeseries() == "2DZT": allow = True return allow def get_real_xy(self, i, j, dimension_list): ''' functions returns values of x,y based on passed indexes i, j ''' if any(dimension_list[-2:-1]) is None: print 'Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)' raise ValueError('Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)') nc = self.mainWidget.get_selected_ncfile_instance() try: x_var = nc.variables[dimension_list[-1]] y_var = nc.variables[dimension_list[-2]] except: print ('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2])) raise ValueError('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2])) x_ratio = (x_var[-1]-x_var[0])/(len(x_var)-1) y_ratio = (y_var[-1]-y_var[0])/(len(y_var)-1) #x[i] = x_var[0]+x_ratio*i #y[j] = y_var[0]+y_ratio*j x = x_var[0] + x_ratio*i y = y_var[0] + y_ratio*j nc.close() return (x, y) def get_axes(self): return self.fig.get_axes() def fast_redraw(self, artist): background = [self.canvas.copy_from_bbox(self.get_axes()[0].bbox)] self.get_axes()[0].draw_artist(artist) self.canvas.restore_region(background) self.canvas.blit(self.get_axes()[0].bbox) self.canvas.update() self.canvas.flush_events()
class Gui(object): def __init__(self, MainWindow): MainWindow.setObjectName("MainWindow") #Set size of window and make it non-resizeable MainWindow.resize(818, 665) MainWindow.setFixedHeight(665) MainWindow.setFixedWidth(818) MainWindow.setWindowTitle("Map Master: Search for the Lost City") MainWindow.setWindowIcon(QIcon("icon_medium.ico")) #Set window backgrounds self.background = QLabel(MainWindow) self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png")) self.backgroundPixmapSettings = QPixmap(normpath( "images/gameMenuSettings2.png")) self.background.setPixmap(self.backgroundPixmapMenu) self.background.setGeometry(QtCore.QRect(0, 0, 818, 665)) self.popupPixmap = QPixmap(normpath("images/popupBG.png")) font = QFont() if "linux" in platform: font.setFamily("Century Schoolbook L") else: font.setFamily("Century Schoolbook") #Stylesheet settings for labels and buttons self.fg = "QLabel {color:black}" self.fgb = "QPushButton {color:black}" self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QStackedWidget(self.centralwidget) self.stackedWidget.setEnabled(True) self.stackedWidget.setObjectName("stackedWidget") #Main Menu page self.menuPage = QWidget() self.menuPage.setObjectName("menuPage") self.startButton = QPushButton(self.menuPage) self.startButton.setStyleSheet(self.fgb) self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60)) self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8)) self.startButton.setObjectName("startButton") font.setPointSize(15) self.startButton.setFont(font) self.loadButton = QPushButton(self.menuPage) self.loadButton.setStyleSheet(self.fgb) self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60)) self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8)) self.loadButton.setObjectName("loadButton") self.loadButton.setFont(font) self.settingsButton = QPushButton(self.menuPage) self.settingsButton.setStyleSheet(self.fgb) self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60)) self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsButton.setObjectName("settingsButton") self.settingsButton.setFont(font) self.quitButton = QPushButton(self.menuPage) self.quitButton.setStyleSheet(self.fgb) self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60)) self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.quitButton.setObjectName("quitButton") self.quitButton.setFont(font) self.instrButton = QPushButton(self.menuPage) self.instrButton.setStyleSheet(self.fgb) self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60)) self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.instrButton.setObjectName("instrButton") self.instrButton.setFont(font) self.stackedWidget.addWidget(self.menuPage) #Settings page self.settingsPage = QWidget() self.settingsPage.setObjectName("settingsPage") self.volumeSlider = QSlider(self.settingsPage) self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30)) self.volumeSlider.setProperty("value", 50) self.volumeSlider.setOrientation(QtCore.Qt.Horizontal) self.volumeSlider.setObjectName("volumeSlider") self.soundLabel = QLabel(self.settingsPage) self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30)) font.setPointSize(20) self.soundLabel.setFont(font) self.soundLabel.setStyleSheet(self.fg) self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8)) self.soundLabel.setAlignment(QtCore.Qt.AlignCenter) self.soundLabel.setObjectName("soundLabel") #Quiet Sound Graphic self.quietGraphic = QLabel(self.settingsPage) self.quietGraphic.setPixmap(QPixmap(normpath( "images/speakerQuiet.png"))) self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80)) self.quietGraphic.setObjectName("quietGraphic") #Loud Sound Graphic self.loudGraphic = QLabel(self.settingsPage) self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png"))) self.loudGraphic.setEnabled(True) self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80)) self.loudGraphic.setObjectName("loudGraphic") self.settingsLabel = QLabel(self.settingsPage) self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.settingsLabel.setFont(font) self.settingsLabel.setStyleSheet(self.fg) self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter) self.settingsLabel.setObjectName("settingsLabel") self.doneButton = QPushButton(self.settingsPage) self.doneButton.setStyleSheet(self.fgb) self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton.setObjectName("doneButton") font.setPointSize(15) self.doneButton.setFont(font) self.stackedWidget.addWidget(self.settingsPage) self.soundManager = Sounds(self.volumeSlider.sliderPosition()) #Main Game page self.mainPage = QWidget() self.mainPage.setObjectName("mainPage") #Person View self.personView = ViewGraphics(self.mainPage) self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500)) self.personView.setObjectName("personView") #Map View self.mapView = ViewGraphics(self.mainPage) self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500)) self.mapView.setObjectName("mapView") #ClueView self.clueView = QLabel(self.mainPage) self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91)) self.clueView.setObjectName("clueView") font.setPointSize(20) self.clueView.setFont(font) self.clueView.setStyleSheet(self.fg) #Map Toggles self.latLongCheck = QCheckBox(self.mainPage) self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41)) self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n" "Longitude", None, QApplication.UnicodeUTF8)) self.latLongCheck.setObjectName("latLongCheck") font.setPointSize(12) self.latLongCheck.setFont(font) self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.colorCheck = QCheckBox(self.mainPage) self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41)) self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n" "Coding", None, QApplication.UnicodeUTF8)) self.colorCheck.setObjectName("colorCheck") self.colorCheck.setFont(font) self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.legendCheck = QCheckBox(self.mainPage) self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22)) self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8)) self.legendCheck.setObjectName("legendCheck") self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus) font.setPointSize(12) self.legendCheck.setFont(font) self.searchButton = QPushButton(self.mainPage) self.searchButton.setStyleSheet(self.fgb) self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55)) self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchButton.setObjectName("searchButton") font.setPointSize(15) self.searchButton.setFont(font) self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus) #Score pieces self.scoreBox = QLabel(self.mainPage) self.scoreBox.setStyleSheet(self.fg) self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41)) self.scoreBox.setObjectName("scoreBox") self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8)) self.scoreBox.setFont(font) self.scoreLabel = QLabel(self.mainPage) self.scoreLabel.setStyleSheet(self.fg) self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17)) self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8)) self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter) self.scoreLabel.setObjectName("scoreLabel") self.scoreLabel.setFont(font) self.popup = ViewGraphics(self.mainPage) self.popup.setStyleSheet( "QGraphicsView {background:transparent;border-style:none}") self.popupImage = self.popup.scene.addPixmap(self.popupPixmap) self.popup.setGeometry(QtCore.QRect(25, 25, 750, 450)) self.popup.setObjectName("popupLabel") font.setPointSize(25) self.popupText = self.popup.scene.addText("", font) self.textColor = QColor('black') self.popupText.setDefaultTextColor(self.textColor) self.popupText.setX(350) self.popupText.setY(225) self.popupImage.setOpacity(0) self.popupText.setOpacity(0) self.stackedWidget.addWidget(self.mainPage) #Help page self.helpPage = QWidget() self.helpPage.setObjectName("helpPage") self.HelpLabel = QLabel(self.helpPage) self.HelpLabel.setStyleSheet(self.fg) self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.HelpLabel.setFont(font) self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter) self.HelpLabel.setObjectName("HelpLabel") self.wInstr = QLabel(self.helpPage) self.wInstr.setStyleSheet(self.fg) self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30)) font.setPointSize(20) self.wInstr.setFont(font) self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8)) self.wInstr.setAlignment(QtCore.Qt.AlignCenter) self.wInstr.setObjectName("wInstr") self.sInstr = QLabel(self.helpPage) self.sInstr.setStyleSheet(self.fg) self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30)) self.sInstr.setFont(font) self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8)) self.sInstr.setAlignment(QtCore.Qt.AlignCenter) self.sInstr.setObjectName("sInstr") self.aInstr = QLabel(self.helpPage) self.aInstr.setStyleSheet(self.fg) self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30)) self.aInstr.setFont(font) self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8)) self.aInstr.setAlignment(QtCore.Qt.AlignCenter) self.aInstr.setObjectName("aInstr") self.dInstr = QLabel(self.helpPage) self.dInstr.setStyleSheet(self.fg) self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30)) self.dInstr.setFont(font) self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8)) self.dInstr.setAlignment(QtCore.Qt.AlignCenter) self.dInstr.setObjectName("dInstr") self.wInstr2 = QLabel(self.helpPage) self.wInstr2.setStyleSheet(self.fg) self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30)) self.wInstr2.setFont(font) self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8)) self.wInstr2.setAlignment(QtCore.Qt.AlignCenter) self.wInstr2.setObjectName("wInstr2") self.sInstr2 = QLabel(self.helpPage) self.sInstr2.setStyleSheet(self.fg) self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30)) self.sInstr2.setFont(font) self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8)) self.sInstr2.setAlignment(QtCore.Qt.AlignCenter) self.sInstr2.setObjectName("sInstr2") self.aInstr2 = QLabel(self.helpPage) self.aInstr2.setStyleSheet(self.fg) self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30)) self.aInstr2.setFont(font) self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8)) self.aInstr2.setAlignment(QtCore.Qt.AlignCenter) self.aInstr2.setObjectName("aInstr2") self.dInstr2 = QLabel(self.helpPage) self.dInstr2.setStyleSheet(self.fg) self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30)) self.dInstr2.setFont(font) self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8)) self.dInstr2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2.setObjectName("dInstr2") self.searchInstr = QPushButton(self.helpPage) self.searchInstr.setStyleSheet(self.fgb) self.searchInstr.setEnabled(True) self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30)) self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchInstr.setAutoDefault(False) self.searchInstr.setDefault(False) self.searchInstr.setFlat(False) self.searchInstr.setObjectName("searchInstr") font.setPointSize(15) self.searchInstr.setFont(font) self.dInstr2_2 = QLabel(self.helpPage) self.dInstr2_2.setStyleSheet(self.fg) self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30)) font.setPointSize(20) self.dInstr2_2.setFont(font) self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8)) self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2_2.setObjectName("dInstr2_2") self.doneButton2 = QPushButton(self.helpPage) self.doneButton2.setStyleSheet(self.fgb) self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton2.setObjectName("doneButton2") font.setPointSize(15) self.doneButton2.setFont(font) self.stackedWidget.addWidget(self.helpPage) #Credits page self.creditsPage = QWidget() self.creditsPage.setObjectName("creditsPage") self.creditsLabel = QLabel(self.creditsPage) self.creditsLabel.setStyleSheet(self.fg) self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.creditsLabel.setFont(font) self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter) self.creditsLabel.setObjectName("creditsLabel") self.credits = QLabel(self.creditsPage) self.credits.setStyleSheet(self.fg) self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400)) font.setPointSize(20) self.credits.setFont(font) self.credits.setText(QApplication.translate("MainWindow", "Gary Lent\n" "Grant Stafford\n" "Jessie Liu\n" "Peter Andrien\n" "Nokia (Qt4 framework)\n" "Riverbank Computing Ltd (PyQt)\n" "Celestial Aeon Project", None, QApplication.UnicodeUTF8)) self.credits.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.credits.setObjectName("credits") self.doneButton3 = QPushButton(self.creditsPage) self.doneButton3.setStyleSheet(self.fgb) self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton3.setObjectName("doneButton3") font.setPointSize(15) self.doneButton3.setFont(font) self.stackedWidget.addWidget(self.creditsPage) #Story page self.storyPage = QWidget() self.storyPage.setObjectName("storyPage") self.storyLabel = QLabel(self.storyPage) self.storyLabel.setStyleSheet(self.fg) self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400)) font.setPointSize(25) self.storyLabel.setFont(font) self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently" " lost my job, but stumbled\n on a clue that may change my life" " \nforever. I've set off on a quest - a quest\n to find a lost city. " "I've found a clue,\n and believe there may be more.\n Help me find " "the lost city. ", None, QApplication.UnicodeUTF8)) self.storyLabel.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.storyLabel.setObjectName("storyLabel") self.nextButton = QPushButton(self.storyPage) self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8)) self.nextButton.setObjectName("nextButton") self.nextButton.setStyleSheet(self.fgb) font.setPointSize(15) self.nextButton.setFont(font) self.stackedWidget.addWidget(self.storyPage) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) #Menu bar self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25)) self.menubar.setObjectName("menubar") self.menuMenu = QMenu(self.menubar) self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8)) self.menuMenu.setObjectName("menuMenu") MainWindow.setMenuBar(self.menubar) self.actionSave_Game = QAction(MainWindow) self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8)) self.actionSave_Game.setObjectName("actionSave_Game") self.actionCredits = QAction(MainWindow) self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.actionCredits.setObjectName("actionCredits") self.actionQuit = QAction(MainWindow) self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.actionQuit.setObjectName("actionQuit") self.actionSettings = QAction(MainWindow) self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.actionSettings.setObjectName("actionSettings") self.actionHelp = QAction(MainWindow) self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.actionHelp.setObjectName("actionHelp") self.actionMain_Menu = QAction(MainWindow) self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8)) self.actionMain_Menu.setObjectName("actionMain_Menu") self.menuMenu.addAction(self.actionSettings) self.menuMenu.addAction(self.actionHelp) self.menuMenu.addAction(self.actionSave_Game) self.menuMenu.addAction(self.actionCredits) self.menuMenu.addAction(self.actionMain_Menu) self.menuMenu.addAction(self.actionQuit) self.menubar.addAction(self.menuMenu.menuAction()) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) self.stackIndex = 0 def retranslateUi(self, MainWindow): pass
class FindReplaceBase(QWidget): """ Base class for both find and replace widgets """ maxHistory = 16 incSearchDone = pyqtSignal(bool) def __init__(self, editorsManager, parent=None): QWidget.__init__(self, parent) self._skip = True self.editorsManager = editorsManager self._currentWidget = None self._isTextEditor = False self._editor = None self._editorUUID = False self.findHistory = GlobalData().project.findHistory self._findBackward = False # Incremental search support self._searchSupport = SearchSupport() self.connect(editorsManager, SIGNAL("tabClosed"), self.__onTabClosed) # Common graphics items self.closeButton = QToolButton(self) self.closeButton.setToolTip("Close the dialog (ESC)") self.closeButton.setIcon(PixmapCache().getIcon("close.png")) self.closeButton.clicked.connect(self.hide) self.findLabel = QLabel(self) self.findLabel.setText("Find:") self.findtextCombo = ComboBoxNoUndo(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.findtextCombo.sizePolicy().hasHeightForWidth()) self.findtextCombo.setSizePolicy(sizePolicy) self.findtextCombo.setEditable(True) self.findtextCombo.setInsertPolicy(QComboBox.InsertAtTop) self.findtextCombo.setAutoCompletion(False) self.findtextCombo.setDuplicatesEnabled(False) self.findtextCombo.setEnabled(False) self.findtextCombo.editTextChanged.connect(self._onEditTextChanged) self.findPrevButton = QToolButton(self) self.findPrevButton.setToolTip("Previous occurrence (Shift+F3)") self.findPrevButton.setIcon(PixmapCache().getIcon("1leftarrow.png")) self.findPrevButton.setIconSize(QSize(24, 16)) self.findPrevButton.setFocusPolicy(Qt.NoFocus) self.findPrevButton.setEnabled(False) self.findNextButton = QToolButton(self) self.findNextButton.setToolTip("Next occurrence (F3)") self.findNextButton.setIcon(PixmapCache().getIcon("1rightarrow.png")) self.findNextButton.setIconSize(QSize(24, 16)) self.findNextButton.setFocusPolicy(Qt.NoFocus) self.findNextButton.setEnabled(False) self.caseCheckBox = QCheckBox(self) self.caseCheckBox.setText("Match case") self.caseCheckBox.setFocusPolicy(Qt.NoFocus) self.caseCheckBox.setEnabled(False) self.caseCheckBox.stateChanged.connect(self._onCheckBoxChange) self.wordCheckBox = QCheckBox(self) self.wordCheckBox.setText("Whole word") self.wordCheckBox.setFocusPolicy(Qt.NoFocus) self.wordCheckBox.setEnabled(False) self.wordCheckBox.stateChanged.connect(self._onCheckBoxChange) self.regexpCheckBox = QCheckBox(self) self.regexpCheckBox.setText("Regexp") self.regexpCheckBox.setFocusPolicy(Qt.NoFocus) self.regexpCheckBox.setEnabled(False) self.regexpCheckBox.stateChanged.connect(self._onCheckBoxChange) self.findtextCombo.lineEdit().returnPressed.connect( self.__findByReturnPressed) self._skip = False return def keyPressEvent(self, event): " Handles the ESC key for the search bar " if event.key() == Qt.Key_Escape: self._searchSupport.clearStartPositions() event.accept() self.hide() activeWindow = self.editorsManager.currentWidget() if activeWindow: activeWindow.setFocus() return def __onTabClosed(self, uuid): " Triggered when a tab is closed " self._searchSupport.delete(uuid) return def setFocus(self): " Overridded setFocus " self.findtextCombo.lineEdit().selectAll() self.findtextCombo.setFocus() return def show(self, text=''): " Overridden show() method " self._skip = True self.findtextCombo.clear() self.findtextCombo.addItems(self.findHistory) self.findtextCombo.setEditText(text) self.findtextCombo.lineEdit().selectAll() self.regexpCheckBox.setChecked(False) self.findtextCombo.setFocus() self._findBackward = False self._skip = False QWidget.show(self) self.activateWindow() self._performSearch(True) return def startHiddenSearch(self, text): " Initiates search without activating the widget " self._skip = True self.findtextCombo.clear() self.findtextCombo.addItems(self.findHistory) self.findtextCombo.setEditText(text) self.findtextCombo.lineEdit().selectAll() self.regexpCheckBox.setChecked(False) self._findBackward = False self._skip = False self._performSearch(True) return def updateStatus(self): " Triggered when the current tab is changed " # Memorize the current environment self._currentWidget = self.editorsManager.currentWidget() self._isTextEditor = self._currentWidget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor, MainWindowTabWidgetBase.VCSAnnotateViewer ] if self._isTextEditor: self._editor = self._currentWidget.getEditor() self._editorUUID = self._currentWidget.getUUID() else: self._editor = None self._editorUUID = "" self.findtextCombo.setEnabled(self._isTextEditor) textAvailable = self.findtextCombo.currentText() != "" self.findPrevButton.setEnabled(self._isTextEditor and textAvailable) self.findNextButton.setEnabled(self._isTextEditor and textAvailable) self.caseCheckBox.setEnabled(self._isTextEditor) self.wordCheckBox.setEnabled(self._isTextEditor) self.regexpCheckBox.setEnabled(self._isTextEditor) return def _resetHighlightOtherEditors(self, uuid): " Resets all the highlights in other editors except of the given " searchAttributes = None if self._searchSupport.hasEditor(uuid): searchAttributes = self._searchSupport.get(uuid) for key in self._searchSupport.editorSearchAttributes: if key == uuid: continue widget = self.editorsManager.getWidgetByUUID(key) if widget is None: continue editor = widget.getEditor() editor.clearSearchIndicators() # Clear what is memorized about the other editors self._searchSupport.editorSearchAttributes = {} if searchAttributes is not None: self._searchSupport.add(uuid, searchAttributes) return def _onCheckBoxChange(self, newState): " Triggered when a search check box state is changed " if self._skip: return self._resetHighlightOtherEditors(self._editorUUID) self._performSearch(False) return def _onEditTextChanged(self, text): " Triggered when the search text has been changed " if self._skip: return self._resetHighlightOtherEditors(self._editorUUID) self._performSearch(False) return def _performSearch(self, fromScratch): " Performs the incremental search " if not self._isTextEditor: return # Memorize the search arguments text = self.findtextCombo.currentText() isRegexp = self.regexpCheckBox.isChecked() isCase = self.caseCheckBox.isChecked() isWord = self.wordCheckBox.isChecked() status = text != "" self.findNextButton.setEnabled(status) self.findPrevButton.setEnabled(status) if fromScratch: self._searchSupport.delete(self._editorUUID) self._initialiseSearchAttributes(self._editorUUID) searchAttributes = self._searchSupport.get(self._editorUUID) if not fromScratch: # We've been searching here already if text == "": # Remove the highlight and scroll back self._editor.clearAllIndicators(self._editor.searchIndicator) self._editor.clearAllIndicators(self._editor.matchIndicator) self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos) self._editor.ensureLineVisible(searchAttributes.firstLine) searchAttributes.match = [-1, -1, -1] self.incSearchDone.emit(False) return matchTarget = self._editor.highlightMatch(text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord) searchAttributes.match = matchTarget if matchTarget != [-1, -1, -1]: # Select the match starting from the end. This will move the # cursor to the beginnig of the match. tgtPos = self._editor.positionFromLineIndex( matchTarget[0], matchTarget[1]) eLine, ePos = self._editor.lineIndexFromPosition( tgtPos + matchTarget[2]) self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1]) self._editor.ensureLineVisible(matchTarget[0]) self.incSearchDone.emit(True) else: # Nothing is found, so scroll back to the original self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos) self._editor.ensureLineVisible(searchAttributes.firstLine) self.incSearchDone.emit(False) return # Brand new editor to search in if text == "": self.incSearchDone.emit(False) return matchTarget = self._editor.highlightMatch(text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord) searchAttributes.match = matchTarget self._searchSupport.add(self._editorUUID, searchAttributes) if matchTarget != [-1, -1, -1]: # Select the match starting from the end. This will move the # cursor to the beginnig of the match. tgtPos = self._editor.positionFromLineIndex( matchTarget[0], matchTarget[1]) eLine, ePos = self._editor.lineIndexFromPosition(tgtPos + matchTarget[2]) self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1]) self._editor.ensureLineVisible(matchTarget[0]) self.incSearchDone.emit(True) return self.incSearchDone.emit(False) return def _initialiseSearchAttributes(self, uuid): " Creates a record if none existed " if self._searchSupport.hasEditor(uuid): return searchAttributes = SearchAttr() searchAttributes.line = self._currentWidget.getLine() searchAttributes.pos = self._currentWidget.getPos() searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(uuid, searchAttributes) return def _advanceMatchIndicator(self, uuid, newLine, newPos, newLength): " Advances the current match indicator for the given editor " if not self._searchSupport.hasEditor(uuid): return searchAttributes = self._searchSupport.get(uuid) match = searchAttributes.match widget = self.editorsManager.getWidgetByUUID(uuid) if widget is None: return editor = widget.getEditor() # Replace the old highlight if searchAttributes.match != [-1, -1, -1]: tgtPos = editor.positionFromLineIndex(match[0], match[1]) editor.clearIndicatorRange(editor.matchIndicator, tgtPos, match[2]) editor.setIndicatorRange(editor.searchIndicator, tgtPos, match[2]) # Memorise new target searchAttributes.match = [newLine, newPos, newLength] self._searchSupport.add(uuid, searchAttributes) # Update the new highlight tgtPos = editor.positionFromLineIndex(newLine, newPos) editor.clearIndicatorRange(editor.searchIndicator, tgtPos, newLength) editor.setIndicatorRange(editor.matchIndicator, tgtPos, newLength) # Select the match from end to the start - this will move the # cursor to the first symbol of the match eLine, ePos = editor.lineIndexFromPosition(tgtPos + newLength) editor.setSelection(eLine, ePos, newLine, newPos) # Move the cursor to the new match editor.ensureLineVisible(newLine) return def onNext(self, clearSBMessage=True): " Triggered when the find next is clicked " if not self.onPrevNext(): return self._findBackward = False if not self.__findNextPrev(clearSBMessage): GlobalData().mainWindow.showStatusBarMessage( "The '" + self.findtextCombo.currentText() + "' was not found.", 0) self.incSearchDone.emit(False) else: self.incSearchDone.emit(True) return def onPrev(self, clearSBMessage=True): " Triggered when the find prev is clicked " if not self.onPrevNext(): return self._findBackward = True if not self.__findNextPrev(clearSBMessage): GlobalData().mainWindow.showStatusBarMessage( "The '" + self.findtextCombo.currentText() + "' was not found.", 0) self.incSearchDone.emit(False) else: self.incSearchDone.emit(True) return def onPrevNext(self): """ Checks prerequisites, saves the history and returns True if the search should be done """ txt = self.findtextCombo.currentText() if txt == "": return False currentWidget = self.editorsManager.currentWidget() if currentWidget.getType() not in \ [ MainWindowTabWidgetBase.PlainTextEditor, MainWindowTabWidgetBase.VCSAnnotateViewer ]: return False return True def __findByReturnPressed(self): " Triggered when 'Enter' or 'Return' is clicked " if self._findBackward: self.onPrev() else: self.onNext() return def __findNextPrev(self, clearSBMessage=True): " Finds the next occurrence of the search text " if not self._isTextEditor: return False # Identify the search start point startLine = self._currentWidget.getLine() startPos = self._currentWidget.getPos() if self._searchSupport.hasEditor(self._editorUUID): searchAttributes = self._searchSupport.get(self._editorUUID) if startLine == searchAttributes.match[ 0 ] and \ startPos == searchAttributes.match[ 1 ]: # The cursor is on the current match, i.e. the user did not # put the focus into the editor and did not move it if not self._findBackward: # The match[ 2 ] gives the length in bytes, not in chars # which could be national i.e. multibytes. So calc the # right length in chars... pos = self._editor.positionFromLineIndex( startLine, startPos) adjustment = len( self._editor.stringAt(pos, searchAttributes.match[2])) startPos = startPos + adjustment else: # The cursor is not at the same position as the last match, # i.e. the user moved it some way # Update the search attributes as if a new search is started searchAttributes.line = startLine searchAttributes.pos = startPos searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) else: # There were no search in this editor searchAttributes = SearchAttr() searchAttributes.line = startLine searchAttributes.pos = startPos searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) # Here: start point has been identified if self.__searchFrom(startLine, startPos, clearSBMessage): # Something new has been found - change the start pos searchAttributes = self._searchSupport.get(self._editorUUID) searchAttributes.line = self._currentWidget.getLine() searchAttributes.pos = self._currentWidget.getPos() searchAttributes.firstLine = self._editor.firstVisibleLine() self._searchSupport.add(self._editorUUID, searchAttributes) return True return False def __searchFrom(self, startLine, startPos, clearSBMessage=True): " Searches starting from the given position " # Memorize the search arguments text = self.findtextCombo.currentText() isRegexp = self.regexpCheckBox.isChecked() isCase = self.caseCheckBox.isChecked() isWord = self.wordCheckBox.isChecked() if not self._findBackward: # Search forward self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1) if len(targets) == 0: GlobalData().mainWindow.showStatusBarMessage( "Reached the end of the document. " "Searching from the beginning...", 0) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos) if len(targets) == 0: searchAttributes = self._searchSupport.get( self._editorUUID) searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) return False # Nothing has matched else: if clearSBMessage: # Hide the 'reached the end of ...' message GlobalData().mainWindow.clearStatusBarMessage(0) # Move the highlight and the cursor to the new match and # memorize a new match self._advanceMatchIndicator(self._editorUUID, targets[0][0], targets[0][1], targets[0][2]) return True # Search backward self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos) if len(targets) == 0: GlobalData().mainWindow.showStatusBarMessage( "Reached the beginning of the document. " "Searching from the end...", 0) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1) if len(targets) == 0: searchAttributes = self._searchSupport.get(self._editorUUID) searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) return False # Nothing has matched else: if clearSBMessage: # Hide the 'reached the beginning of ...' message GlobalData().mainWindow.clearStatusBarMessage(0) # Move the highlight and the cursor to the new match and # memorize a new match index = len(targets) - 1 self._advanceMatchIndicator(self._editorUUID, targets[index][0], targets[index][1], targets[index][2]) return True def _addToHistory(self, combo, history, text): " Adds the item to the history. Returns true if need to add. " text = str(text) changes = False if text in history: if history[0] != text: changes = True history.remove(text) history.insert(0, text) else: changes = True history.insert(0, text) if len(history) > self.maxHistory: changes = True history = history[:self.maxHistory] self._skip = True combo.clear() combo.addItems(history) self._skip = False return changes def getLastSearchString(self): " Provides the string which was searched last time " return self.findtextCombo.currentText()
class GuiMain(object): def __init__(self, data): self.data = data self.loadSave = False def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") #Set size of window and make it non-resizeable MainWindow.resize(818, 665) MainWindow.setFixedHeight(665) MainWindow.setFixedWidth(818) MainWindow.setWindowTitle("Map Master: Search for the Lost City") MainWindow.setWindowIcon(QIcon("icon_medium.ico")) #Set window backgrounds self.background = QLabel(MainWindow) self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png")) self.backgroundPixmapSettings = QPixmap(normpath( "images/gameMenuSettings2.png")) self.background.setPixmap(self.backgroundPixmapMenu) self.background.setGeometry(QtCore.QRect(0, 0, 818, 665)) font = QFont() if "linux" in platform: font.setFamily("Century Schoolbook L") else: font.setFamily("Century Schoolbook") #Stylesheet settings for labels and buttons self.fg = "QLabel {color:black}" self.fgb = "QPushButton {color:black}" self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QStackedWidget(self.centralwidget) self.stackedWidget.setEnabled(True) self.stackedWidget.setObjectName("stackedWidget") #Main Menu page self.menuPage = QWidget() self.menuPage.setObjectName("menuPage") self.startButton = QPushButton(self.menuPage) self.startButton.setStyleSheet(self.fgb) self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60)) self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8)) self.startButton.setObjectName("startButton") font.setPointSize(15) self.startButton.setFont(font) self.loadButton = QPushButton(self.menuPage) self.loadButton.setStyleSheet(self.fgb) self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60)) self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8)) self.loadButton.setObjectName("loadButton") self.loadButton.setFont(font) self.settingsButton = QPushButton(self.menuPage) self.settingsButton.setStyleSheet(self.fgb) self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60)) self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsButton.setObjectName("settingsButton") self.settingsButton.setFont(font) self.quitButton = QPushButton(self.menuPage) self.quitButton.setStyleSheet(self.fgb) self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60)) self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.quitButton.setObjectName("quitButton") self.quitButton.setFont(font) self.instrButton = QPushButton(self.menuPage) self.instrButton.setStyleSheet(self.fgb) self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60)) self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.instrButton.setObjectName("instrButton") self.instrButton.setFont(font) self.stackedWidget.addWidget(self.menuPage) #Settings page self.settingsPage = QWidget() self.settingsPage.setObjectName("settingsPage") self.volumeSlider = QSlider(self.settingsPage) self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30)) self.volumeSlider.setProperty("value", 50) self.volumeSlider.setOrientation(QtCore.Qt.Horizontal) self.volumeSlider.setObjectName("volumeSlider") self.soundLabel = QLabel(self.settingsPage) self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30)) font.setPointSize(20) self.soundLabel.setFont(font) self.soundLabel.setStyleSheet(self.fg) self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8)) self.soundLabel.setAlignment(QtCore.Qt.AlignCenter) self.soundLabel.setObjectName("soundLabel") #Quiet Sound Graphic self.quietGraphic = QLabel(self.settingsPage) self.quietGraphic.setPixmap(QPixmap(normpath( "images/speakerQuiet.png"))) self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80)) self.quietGraphic.setObjectName("quietGraphic") #Loud Sound Graphic self.loudGraphic = QLabel(self.settingsPage) self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png"))) self.loudGraphic.setEnabled(True) self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80)) self.loudGraphic.setObjectName("loudGraphic") self.settingsLabel = QLabel(self.settingsPage) self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.settingsLabel.setFont(font) self.settingsLabel.setStyleSheet(self.fg) self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter) self.settingsLabel.setObjectName("settingsLabel") self.doneButton = QPushButton(self.settingsPage) self.doneButton.setStyleSheet(self.fgb) self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton.setObjectName("doneButton") font.setPointSize(15) self.doneButton.setFont(font) self.stackedWidget.addWidget(self.settingsPage) self.soundManager = Sounds(self.volumeSlider.sliderPosition()) #Main Game page self.mainPage = QWidget() self.mainPage.setObjectName("mainPage") #Person View self.personView = ViewGraphics(self.mainPage) self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500)) self.personView.setObjectName("personView") #Map View self.mapView = ViewGraphics(self.mainPage) self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500)) self.mapView.setObjectName("mapView") #ClueView self.clueView = QLabel(self.mainPage) self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91)) self.clueView.setObjectName("clueView") font.setPointSize(20) self.clueView.setFont(font) self.clueView.setStyleSheet(self.fg) #Map Toggles self.latLongCheck = QCheckBox(self.mainPage) self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41)) self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n" "Longitude", None, QApplication.UnicodeUTF8)) self.latLongCheck.setObjectName("latLongCheck") font.setPointSize(12) self.latLongCheck.setFont(font) self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.colorCheck = QCheckBox(self.mainPage) self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41)) self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n" "Coding", None, QApplication.UnicodeUTF8)) self.colorCheck.setObjectName("colorCheck") self.colorCheck.setFont(font) self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.legendCheck = QCheckBox(self.mainPage) self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22)) self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8)) self.legendCheck.setObjectName("legendCheck") self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus) font.setPointSize(12) self.legendCheck.setFont(font) self.searchButton = QPushButton(self.mainPage) self.searchButton.setStyleSheet(self.fgb) self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55)) self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchButton.setObjectName("searchButton") font.setPointSize(15) self.searchButton.setFont(font) self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus) #Score pieces self.scoreBox = QLabel(self.mainPage) self.scoreBox.setStyleSheet(self.fg) self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41)) self.scoreBox.setObjectName("scoreBox") self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8)) self.scoreBox.setFont(font) self.scoreLabel = QLabel(self.mainPage) self.scoreLabel.setStyleSheet(self.fg) self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17)) self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8)) self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter) self.scoreLabel.setObjectName("scoreLabel") self.scoreLabel.setFont(font) self.popupLabel = QLabel(self.mainPage) self.popupLabel.setGeometry(QtCore.QRect(25, 25, 750, 450)) self.popupLabel.setObjectName("popupLabel") #This is temporary code to insert a popup. self.popupLabel.setStyleSheet( "QLabel { background-color: tan ; color : black }") self.popupLabel.setAlignment(QtCore.Qt.AlignCenter) font.setPointSize(36) self.popupLabel.setFont(font) self.popupLabel.setText("") self.popupLabel.setVisible(False) self.stackedWidget.addWidget(self.mainPage) #Help page self.helpPage = QWidget() self.helpPage.setObjectName("helpPage") self.HelpLabel = QLabel(self.helpPage) self.HelpLabel.setStyleSheet(self.fg) self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.HelpLabel.setFont(font) self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter) self.HelpLabel.setObjectName("HelpLabel") self.wInstr = QLabel(self.helpPage) self.wInstr.setStyleSheet(self.fg) self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30)) font.setPointSize(20) self.wInstr.setFont(font) self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8)) self.wInstr.setAlignment(QtCore.Qt.AlignCenter) self.wInstr.setObjectName("wInstr") self.sInstr = QLabel(self.helpPage) self.sInstr.setStyleSheet(self.fg) self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30)) self.sInstr.setFont(font) self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8)) self.sInstr.setAlignment(QtCore.Qt.AlignCenter) self.sInstr.setObjectName("sInstr") self.aInstr = QLabel(self.helpPage) self.aInstr.setStyleSheet(self.fg) self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30)) self.aInstr.setFont(font) self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8)) self.aInstr.setAlignment(QtCore.Qt.AlignCenter) self.aInstr.setObjectName("aInstr") self.dInstr = QLabel(self.helpPage) self.dInstr.setStyleSheet(self.fg) self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30)) self.dInstr.setFont(font) self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8)) self.dInstr.setAlignment(QtCore.Qt.AlignCenter) self.dInstr.setObjectName("dInstr") self.wInstr2 = QLabel(self.helpPage) self.wInstr2.setStyleSheet(self.fg) self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30)) self.wInstr2.setFont(font) self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8)) self.wInstr2.setAlignment(QtCore.Qt.AlignCenter) self.wInstr2.setObjectName("wInstr2") self.sInstr2 = QLabel(self.helpPage) self.sInstr2.setStyleSheet(self.fg) self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30)) self.sInstr2.setFont(font) self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8)) self.sInstr2.setAlignment(QtCore.Qt.AlignCenter) self.sInstr2.setObjectName("sInstr2") self.aInstr2 = QLabel(self.helpPage) self.aInstr2.setStyleSheet(self.fg) self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30)) self.aInstr2.setFont(font) self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8)) self.aInstr2.setAlignment(QtCore.Qt.AlignCenter) self.aInstr2.setObjectName("aInstr2") self.dInstr2 = QLabel(self.helpPage) self.dInstr2.setStyleSheet(self.fg) self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30)) self.dInstr2.setFont(font) self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8)) self.dInstr2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2.setObjectName("dInstr2") self.searchInstr = QPushButton(self.helpPage) self.searchInstr.setStyleSheet(self.fgb) self.searchInstr.setEnabled(True) self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30)) self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchInstr.setAutoDefault(False) self.searchInstr.setDefault(False) self.searchInstr.setFlat(False) self.searchInstr.setObjectName("searchInstr") font.setPointSize(15) self.searchInstr.setFont(font) self.dInstr2_2 = QLabel(self.helpPage) self.dInstr2_2.setStyleSheet(self.fg) self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30)) font.setPointSize(20) self.dInstr2_2.setFont(font) self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8)) self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2_2.setObjectName("dInstr2_2") self.doneButton2 = QPushButton(self.helpPage) self.doneButton2.setStyleSheet(self.fgb) self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton2.setObjectName("doneButton2") font.setPointSize(15) self.doneButton2.setFont(font) self.stackedWidget.addWidget(self.helpPage) #Credits page self.creditsPage = QWidget() self.creditsPage.setObjectName("creditsPage") self.creditsLabel = QLabel(self.creditsPage) self.creditsLabel.setStyleSheet(self.fg) self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.creditsLabel.setFont(font) self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter) self.creditsLabel.setObjectName("creditsLabel") self.credits = QLabel(self.creditsPage) self.credits.setStyleSheet(self.fg) self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400)) font.setPointSize(20) self.credits.setFont(font) self.credits.setText(QApplication.translate("MainWindow", "Gary Lent\n" "Grant Stafford\n" "Jessie Liu\n" "Peter Andrien\n" "Nokia (Qt4 framework)\n" "Riverbank Computing Ltd (PyQt)\n" "Celestial Aeon Project", None, QApplication.UnicodeUTF8)) self.credits.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.credits.setObjectName("credits") self.doneButton3 = QPushButton(self.creditsPage) self.doneButton3.setStyleSheet(self.fgb) self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton3.setObjectName("doneButton3") font.setPointSize(15) self.doneButton3.setFont(font) self.stackedWidget.addWidget(self.creditsPage) #Story page self.storyPage = QWidget() self.storyPage.setObjectName("storyPage") self.storyLabel = QLabel(self.storyPage) self.storyLabel.setStyleSheet(self.fg) self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400)) font.setPointSize(25) self.storyLabel.setFont(font) self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently" " lost my job, but stumbled\n on a clue that may change my life" " \nforever. I've set off on a quest - a quest\n to find a lost city. " "I've found a clue,\n and believe there may be more.\n Help me find " "the lost city. ", None, QApplication.UnicodeUTF8)) self.storyLabel.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.storyLabel.setObjectName("storyLabel") self.nextButton = QPushButton(self.storyPage) self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8)) self.nextButton.setObjectName("nextButton") self.nextButton.setStyleSheet(self.fgb) font.setPointSize(15) self.nextButton.setFont(font) self.stackedWidget.addWidget(self.storyPage) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) #Menu bar self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25)) self.menubar.setObjectName("menubar") self.menuMenu = QMenu(self.menubar) self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8)) self.menuMenu.setObjectName("menuMenu") MainWindow.setMenuBar(self.menubar) self.actionSave_Game = QAction(MainWindow) self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8)) self.actionSave_Game.setObjectName("actionSave_Game") self.actionCredits = QAction(MainWindow) self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.actionCredits.setObjectName("actionCredits") self.actionQuit = QAction(MainWindow) self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.actionQuit.setObjectName("actionQuit") self.actionSettings = QAction(MainWindow) self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.actionSettings.setObjectName("actionSettings") self.actionHelp = QAction(MainWindow) self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.actionHelp.setObjectName("actionHelp") self.actionMain_Menu = QAction(MainWindow) self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8)) self.actionMain_Menu.setObjectName("actionMain_Menu") self.menuMenu.addAction(self.actionSettings) self.menuMenu.addAction(self.actionHelp) self.menuMenu.addAction(self.actionSave_Game) self.menuMenu.addAction(self.actionCredits) self.menuMenu.addAction(self.actionMain_Menu) self.menuMenu.addAction(self.actionQuit) self.menubar.addAction(self.menuMenu.menuAction()) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) #These are the slots and signals to connect buttons to other functions self.location = 0 QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), MainWindow.close) QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("released()"), MainWindow.close) QtCore.QObject.connect(self.settingsButton, QtCore.SIGNAL("released()"), self.setSettings) QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL("triggered()"), self.setSettings) QtCore.QObject.connect(self.loadButton, QtCore.SIGNAL("released()"), self.load_file_dialog) QtCore.QObject.connect(self.actionSave_Game, QtCore.SIGNAL("triggered()"), self.save_file_dialog) QtCore.QObject.connect(self.doneButton, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.startButton, QtCore.SIGNAL("released()"), self.newGame) QtCore.QObject.connect(self.actionMain_Menu, QtCore.SIGNAL("triggered()"), self.setMain) QtCore.QObject.connect(self.actionHelp, QtCore.SIGNAL("triggered()"), self.setInstructions) QtCore.QObject.connect(self.instrButton, QtCore.SIGNAL("released()"), self.setInstructions) QtCore.QObject.connect(self.doneButton2, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.doneButton3, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.actionCredits, QtCore.SIGNAL("triggered()"), self.setCredits) self.latLongCheck.stateChanged.connect(self.latLong) self.colorCheck.stateChanged.connect(self.colorize) self.legendCheck.stateChanged.connect(self.legend) QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("released()"), self.doSearch) QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL("released()"), self.storyButton) self.volumeSlider.sliderMoved.connect(self.setVol) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): pass #Custom signals are here def setSettings(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(1) def setInstructions(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(3) def setCredits(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(4) def goBack(self): self.stackedWidget.setCurrentIndex(self.location) if self.location == 0: self.background.setPixmap(self.backgroundPixmapMenu) else: None #Should be something here later. def load_file_dialog(self): fd = QFileDialog() self.filename = fd.getOpenFileName(None, "Load Saved Game", "saves", "MapMaster Save files (*.save)") if isfile(self.filename): self.loadSaved = True self.newGame() def save_file_dialog(self): filename = QFileDialog.getSaveFileName(None, "Save Game", "saves", "MapMaster Save files (*.save)") if filename == "": print "No file specified!" else: if ".save" in filename: self.fname = open(filename, "w") else: self.fname = open(filename + ".save",'w') self.fname.write("Hello") self.fname.close() def newGame(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(5) self.location = 5 def storyButton(self): self.stackedWidget.setCurrentIndex(2) self.location = 2 self.soundManager.switchSongs(self.location) def setMain(self): self.save_file_dialog() self.background.setPixmap(self.backgroundPixmapMenu) self.stackedWidget.setCurrentIndex(0) self.location = 0 self.soundManager.switchSongs(self.location) def latLong(self): if self.latLongCheck.isChecked(): print "Lat/long overlay on" else: print "Lat/long overlay off" self.data.overlays['latLongOverlay'].mViewObj.setVisible( self.latLongCheck.isChecked()) def colorize(self): if self.colorCheck.isChecked(): print "Color overlay on" else: print "Color overlay off" self.data.overlays['colorOverlay'].mViewObj.setVisible( self.colorCheck.isChecked()) def legend(self): if self.legendCheck.isChecked(): print "Legend overlay on" else: print "Legend overlay off" self.data.overlays['legendOverlay'].mViewObj.setVisible( self.legendCheck.isChecked()) def setVol(self): self.soundManager.setVolume(self.volumeSlider.sliderPosition()) def doSearch(self): searchLandmark(self.data)
class Window(QMainWindow): def __init__(self, parent=None): super(Window, self).__init__(parent) global time_start, x_arr, y_arr, arduino_connected # Flag variables self.filename = '' self.array_len = len(x_arr) self.clean_recorded_data = True self.recording_status = False self.file_saved = False self.recorded_list = [] self.record_cell_start = None self.record_cell_end = None self.follow_plot = True # Window Properties self.setWindowTitle("Arduino Plotter") self.setWindowIcon(QIcon(":/window_icon.png")) self.resize(800, 600) # Plot Settings and Creation self.plot_settings = dict(plotLineWidth=1, horizontalGrid=True, verticalGrid=True, gridOpacity=1, lineColor='b', arrayPlotSize=25, serialBaud=115200, separator=' ') pg.setConfigOption('background', 'w') self.load_settings() self.createPlot() # Create Bars self.createBars() # Get list of arduino devices self.updateDevicesList() # Add Widgets to Main Window self.addWidgets() # Add bar to display status messages status = self.statusBar() self.sizeLabel = QLabel() self.sizeLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) status.addPermanentWidget(self.sizeLabel) status.setSizeGripEnabled(False) # Start Thread & program time count(x axis) time_start = time.time() self.read_serial_thread = ReadSerialThread( self.arduino_combobox.currentText(), self.plot_settings['serialBaud'], self) self.read_serial_thread.start() self.update() def load_settings(self): settings = QSettings() self.plot_settings['horizontalGrid'] = settings.value( "horizontalGrid", self.plot_settings['horizontalGrid']).toBool() self.plot_settings['verticalGrid'] = settings.value( "verticalGrid", self.plot_settings['verticalGrid']).toBool() self.plot_settings['plotLineWidth'] = settings.value( "plotLineWidth", self.plot_settings['plotLineWidth']).toInt()[0] self.plot_settings['gridOpacity'] = settings.value( "gridOpacity", self.plot_settings['gridOpacity']).toFloat()[0] self.plot_settings['lineColor'] = unicode( settings.value("lineColor", self.plot_settings['lineColor']).toString()) self.plot_settings['arrayPlotSize'] = settings.value( "arrayPlotSize", self.plot_settings['arrayPlotSize']).toInt()[0] self.plot_settings['serialBaud'] = settings.value( "serialBaud", self.plot_settings['serialBaud']).toInt()[0] self.plot_settings['separator'] = settings.value( "separator", self.plot_settings['separator']).toString() # Save settings values def closeEvent(self, event): settings = QSettings() settings.setValue('horizontalGrid', QVariant(self.plot_settings['horizontalGrid'])) settings.setValue('verticalGrid', QVariant(self.plot_settings['verticalGrid'])) settings.setValue('plotLineWidth', QVariant(self.plot_settings['plotLineWidth'])) settings.setValue('gridOpacity', QVariant(self.plot_settings['gridOpacity'])) settings.setValue('lineColor', QVariant(self.plot_settings['lineColor'])) settings.setValue('arrayPlotSize', QVariant(self.plot_settings['arrayPlotSize'])) settings.setValue('serialBaud', QVariant(self.plot_settings['serialBaud'])) settings.setValue('separator', QVariant(self.plot_settings['separator'])) # Plot Creation def createPlot(self): self.plot_zone = pg.PlotWidget() self.pen = pg.mkPen(width=self.plot_settings['plotLineWidth'], color=self.plot_settings['lineColor'][0]) self.plot_zone.plotItem.showGrid(self.plot_settings['verticalGrid'], self.plot_settings['horizontalGrid'], self.plot_settings['gridOpacity']) self.plot_zone.plotItem.ctrlMenu = None self.plot_zone.setAutoPan(True) # self.plot_zone.plotItem.ctrlMenu # self.plot_zone.plotItem.enableAutoRange(enable=0.2) # self.plot_zone.autoRange() self.plot_zone.setXRange(0, 600) # self.plot_zone.setLabels(left=('Signal', 'V'), bottom=('Time')) self.plot_zone.setYRange(0, 5) # self.plot_zone.setMouseEnabled(x=False) self.plot_zone.scene().contextMenu = None # Create Bars # TODO Add Info button def createBars(self): # Create Bar1 controls_toolbar = self.addToolBar("Controls") controls_toolbar.setObjectName("ControlsToolBar") # Create Bar2 arduino_toolbar = self.addToolBar("Arduino") arduino_toolbar.setObjectName("ArduinoToolBar") # Add Elements to Bar1 # Record & Pause self.record_pause = QAction(QIcon(":/rec.png"), "&Rec", self) self.record_pause.setShortcut("Ctrl+R") self.record_pause.setToolTip('Record') self.record_pause.triggered.connect(self.recording) # Stop self.stop = QAction(QIcon(":/stop.png"), "&Detener", self) self.stop.setShortcut("Ctrl+Alt+D") self.stop.setToolTip('Stop') self.stop.triggered.connect(self.stopRecording) # Save self.save_file = QAction(QIcon(":/save.png"), "&Save", self) self.save_file.setShortcut(QKeySequence.Save) self.save_file.setToolTip('Save') self.save_file.triggered.connect(self.saveFile) # Save As self.save_as = QAction(QIcon(":/save_as.png"), "Save As", self) self.save_as.setShortcut(QKeySequence.SaveAs) self.save_as.setToolTip('Save As') self.save_as.triggered.connect(self.saveFileAs) # Configurations self.configurations = QAction(QIcon(":/configs.png"), "&Configurations", self) self.configurations.setShortcut("Ctrl+Alt+S") self.configurations.setToolTip('Settings') self.configurations.triggered.connect(self.changeSettings) # Add buttons to bar controls_toolbar.addAction(self.record_pause) controls_toolbar.addAction(self.stop) controls_toolbar.addAction(self.save_file) controls_toolbar.addAction(self.save_as) controls_toolbar.addAction(self.configurations) # Arduino ComboBox self.arduino_combobox = QComboBox() self.arduino_combobox.setToolTip('Select Arduino') self.arduino_combobox.setFocusPolicy(Qt.NoFocus) self.arduino_combobox.activated.connect(self.updateChoosenArduino) # Update List of Arduino devices self.reload = QAction(QIcon(":/reload.png"), "Reload", self) self.reload.setShortcut(QKeySequence.Refresh) self.reload.setToolTip('Reload Devices') self.reload.triggered.connect(self.updateDevicesList) # Timer Label self.timer_label = QLabel() self.timer_label.setText(' 00:00') # Info button for dialog self.info = QAction(QIcon(":/info.png"), "Reload", self) self.info.setShortcut(QKeySequence.HelpContents) self.info.setToolTip('Help') self.info.triggered.connect(self.showInfo) # Follow checkbox self.follow_label = QLabel("Follow Plot") self.follow_checkbox = QCheckBox() # self.arduino_combobox.setToolTip('Select Arduino') self.follow_checkbox.setFocusPolicy(Qt.NoFocus) self.follow_checkbox.clicked.connect(self.change_follow_status) self.follow_checkbox.setChecked(True) arduino_toolbar.addWidget(self.arduino_combobox) arduino_toolbar.addAction(self.reload) arduino_toolbar.addWidget(self.timer_label) arduino_toolbar.addAction(self.info) arduino_toolbar.addWidget(self.follow_checkbox) arduino_toolbar.addWidget(self.follow_label) # Show Info(Help) dialog def showInfo(self): self.info_dialog = InfoDialog(self) self.info_dialog.show() def change_follow_status(self): if self.follow_checkbox.isChecked(): self.follow_plot = True else: self.follow_plot = False # Update arduino list def updateDevicesList(self): device_list = serial.tools.list_ports.comports() current_arduino = self.arduino_combobox.currentText() self.arduino_combobox.clear() device_index = 0 for device in sorted(device_list): self.arduino_combobox.addItem(device.device) if device.device == current_arduino: self.arduino_combobox.setCurrentIndex(device_index) device_index = device_index + 1 # Update selected arduino def updateChoosenArduino(self): self.restart_values() # Add Widgets def addWidgets(self): self.widget = QWidget() self.setCentralWidget(self.widget) vbox_layout = QVBoxLayout() vbox_layout.addWidget(self.plot_zone) vbox_layout.setContentsMargins(5, 5, 5, 0) self.widget.setLayout(vbox_layout) # Saves indexes of recorded items, thus saves memory def recording(self): global time_start, x_arr, y_arr, arduino_connected status = self.statusBar() # If recording is "Stopped" clear data and start recording if self.clean_recorded_data: mutex.lock() del self.recorded_list[:] del x_arr[:] del y_arr[:] self.array_len = 0 width_visible = self.plot_zone.visibleRange().width() height_visible = self.plot_zone.visibleRange().height() bottom_visible = self.plot_zone.visibleRange().top() # self.plot_zone.visibleRange().setRect(0, 0, 150, 10) # print self.plot_zone.visibleRange() rect_me = QRectF(0, 0, width_visible, 5) self.plot_zone.setRange(rect=rect_me, disableAutoRange=True, xRange=(0, (0 + width_visible)), padding=0, yRange=(bottom_visible, bottom_visible + height_visible)) self.clean_recorded_data = False mutex.unlock() # Start Recording if not self.recording_status: self.record_pause.setIcon(QIcon(':/pause.png')) status.showMessage('Recording') mutex.lock() if x_arr: self.record_cell_start = len(x_arr) - 1 else: self.record_cell_start = len(x_arr) self.recording_status = True mutex.unlock() else: # Pause Recording self.record_pause.setIcon(QIcon(':/rec.png')) status.showMessage('Paused') mutex.lock() # Check if x_arr has no data if x_arr: self.record_cell_end = len(x_arr) - 1 else: self.record_cell_end = len(x_arr) self.recorded_list.append( [self.record_cell_start, self.record_cell_end]) self.recording_status = False mutex.unlock() # Update Arduino status and plot def update(self): global x_arr, y_arr, arduino_connected # self.plot_zone.sceneObj.sigMouseHover.connect(self.me) if arduino_connected: self.sizeLabel.setText('Arduino Connected') self.sizeLabel.setStyleSheet('color:green') mutex.lock() # print ("dasdasd",len(x_arr)) # print ("self", self.array_len) #if not len(x_arr) % self.plot_settings['arrayPlotSize'] and len(x_arr) != 0: #print self.array_len if len(x_arr) - self.array_len >= 50 and len(x_arr) != 0: self.array_len = len(x_arr) try: self.plot_zone.plot( x_arr[:-(self.plot_settings['arrayPlotSize'] + 1)], y_arr[:-(self.plot_settings['arrayPlotSize'] + 1)], clear=True, pen=self.pen) except Exception: if len(x_arr) > len(y_arr): x_arr.pop() else: y_arr.pop() self.plot_zone.plot( x_arr[:-(self.plot_settings['arrayPlotSize'] + 1)], y_arr[:-(self.plot_settings['arrayPlotSize'] + 1)], clear=True, pen=self.pen) #self.plot_zone.setXRange(x_arr[-1:][0] - self.plot_zone.visibleRange().width(), x_arr[-1:][0]) if self.follow_plot: if not (self.plot_zone.visibleRange().left() < x_arr[-1:][0] < self.plot_zone.visibleRange().right()): width_visible = self.plot_zone.visibleRange().width() height_visible = self.plot_zone.visibleRange().height() bottom_visible = self.plot_zone.visibleRange().top() # self.plot_zone.visibleRange().setRect(0, 0, 150, 10) # print self.plot_zone.visibleRange() rect_me = QRectF(x_arr[-1:][0], 0, width_visible, 5) #print rect_me #self.plot_zone.setXRange(x_arr[-1:][0], x_arr[-1:][0] + self.range_x) #self.plot_zone.setRange() #print "MOVE" #print bottom_visible #print height_visible #dest = self.plot_zone.visibleRange().width() #print range_x #print dest #print x_arr[-1:][0] self.plot_zone.setRange( rect=rect_me, disableAutoRange=True, xRange=(x_arr[-1:][0], (x_arr[-1:][0] + width_visible)), padding=0, yRange=(bottom_visible, bottom_visible + height_visible)) #self.plot_zone.sceneObj.sigMouseClicked.connect(self.me) #self.plot_zone.sceneObj.mouseMoveEvent(3) #print self.plot_zone.visibleRange() #range_me = self.plot_zone.visibleRange() #self.plot_zone.sigRangeChanged.connect(self.me) #self.plot_zone.sigYRangeChanged.connect(self.me) mutex.unlock() else: self.sizeLabel.setText('Arduino Disconnected') self.sizeLabel.setStyleSheet('color:red') # Updates the GUI timer time_to_display = int(round(time.time() - time_start, 2)) if time_to_display >= 60: self.timer_label.setText(' ' + str(time_to_display / 60) + ":" + str(time_to_display % 60)) else: if len(str(time_to_display)) == 1: self.timer_label.setText(" " + '0' + ':0' + str(time_to_display)) else: self.timer_label.setText(" " + '0' + ':' + str(time_to_display)) # Call myself every 50milliseconds timer = QTimer() timer.singleShot(100, self.update) # Stops recording def stopRecording(self): mutex.lock() if self.recording_status: if x_arr: self.record_cell_end = len(x_arr) - 1 else: self.record_cell_end = len(x_arr) self.recorded_list.append( [self.record_cell_start, self.record_cell_end]) mutex.unlock() self.clean_recorded_data = True self.recording_status = False self.record_pause.setIcon(QIcon(':/rec.png')) status = self.statusBar() status.showMessage('Stopped') # Save file method def saveFile(self): if not self.file_saved: self.saveFileAs() else: self.writeDataToFile('w') # Save as method def saveFileAs(self): my_home = os.path.expanduser('~') self.filename = QFileDialog.getSaveFileName( self, 'Save As', os.path.join(my_home, "new_file.dat"), "", "", QFileDialog.DontUseNativeDialog) self.writeDataToFile('w') # Write data to file def writeDataToFile(self, open_mode): global x_arr, y_arr try: if self.filename: file_obj = open(self.filename, open_mode) for pair in self.recorded_list: list_x = x_arr[pair[0]:pair[1]] list_y = y_arr[pair[0]:pair[1]] for elem in zip(list_x, list_y): # TODO Check if separator works file_obj.write( str(elem[0]) + self.plot_settings['separator'] + str(elem[1]) + '\n') file_obj.close() self.file_saved = True except (IOError, OSError) as error_file: message = QMessageBox.critical(self, 'Message', str(error_file), QMessageBox.Ok) # message.show() self.filename = '' self.file_saved = False # Create and show settings dialog def changeSettings(self): self.settings_dialog = SettingsDialog(self.plot_settings, self.refreshSettings, self) self.settings_dialog.show() # Refresh settings def refreshSettings(self): self.pen = pg.mkPen(width=self.plot_settings['plotLineWidth'], color=self.plot_settings['lineColor'][0]) self.plot_zone.plotItem.showGrid(self.plot_settings['verticalGrid'], self.plot_settings['horizontalGrid'], self.plot_settings['gridOpacity']) # Restart values and kills when new arduino connection is selected def restart_values(self): global x_arr, y_arr print('killing') self.read_serial_thread.__del__() mutex.lock() self.array_len = 0 del x_arr[:] del y_arr[:] #print x_arr del self.recorded_list[:] #print "clean" width_visible = self.plot_zone.visibleRange().width() height_visible = self.plot_zone.visibleRange().height() bottom_visible = self.plot_zone.visibleRange().top() # self.plot_zone.visibleRange().setRect(0, 0, 150, 10) #print self.plot_zone.visibleRange() rect_me = QRectF(0, 0, width_visible, 5) self.plot_zone.setRange(rect=rect_me, disableAutoRange=True, xRange=(0, (0 + width_visible)), padding=0, yRange=(bottom_visible, bottom_visible + height_visible)) mutex.unlock() #print "clean out" self.read_serial_thread = ReadSerialThread( self.arduino_combobox.currentText(), self.plot_settings['serialBaud'], self) self.read_serial_thread.start()
class FindReplaceBase(QWidget): """ Base class for both find and replace widgets """ maxHistory = 16 incSearchDone = pyqtSignal(bool) def __init__(self, editorsManager, parent=None): QWidget.__init__(self, parent) self._skip = True self.editorsManager = editorsManager self._currentWidget = None self._isTextEditor = False self._editor = None self._editorUUID = False self.findHistory = GlobalData().project.findHistory self._findBackward = False # Incremental search support self._searchSupport = SearchSupport() self.connect(editorsManager, SIGNAL("tabClosed"), self.__onTabClosed) # Common graphics items self.closeButton = QToolButton(self) self.closeButton.setToolTip("Close the dialog (ESC)") self.closeButton.setIcon(PixmapCache().getIcon("close.png")) self.closeButton.clicked.connect(self.hide) self.findLabel = QLabel(self) self.findLabel.setText("Find:") self.findtextCombo = ComboBoxNoUndo(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.findtextCombo.sizePolicy().hasHeightForWidth()) self.findtextCombo.setSizePolicy(sizePolicy) self.findtextCombo.setEditable(True) self.findtextCombo.setInsertPolicy(QComboBox.InsertAtTop) self.findtextCombo.setAutoCompletion(False) self.findtextCombo.setDuplicatesEnabled(False) self.findtextCombo.setEnabled(False) self.findtextCombo.editTextChanged.connect(self._onEditTextChanged) self.findPrevButton = QToolButton(self) self.findPrevButton.setToolTip("Previous occurrence (Shift+F3)") self.findPrevButton.setIcon(PixmapCache().getIcon("1leftarrow.png")) self.findPrevButton.setIconSize(QSize(24, 16)) self.findPrevButton.setFocusPolicy(Qt.NoFocus) self.findPrevButton.setEnabled(False) self.findNextButton = QToolButton(self) self.findNextButton.setToolTip("Next occurrence (F3)") self.findNextButton.setIcon(PixmapCache().getIcon("1rightarrow.png")) self.findNextButton.setIconSize(QSize(24, 16)) self.findNextButton.setFocusPolicy(Qt.NoFocus) self.findNextButton.setEnabled(False) self.caseCheckBox = QCheckBox(self) self.caseCheckBox.setText("Match case") self.caseCheckBox.setFocusPolicy(Qt.NoFocus) self.caseCheckBox.setEnabled(False) self.caseCheckBox.stateChanged.connect(self._onCheckBoxChange) self.wordCheckBox = QCheckBox(self) self.wordCheckBox.setText("Whole word") self.wordCheckBox.setFocusPolicy(Qt.NoFocus) self.wordCheckBox.setEnabled(False) self.wordCheckBox.stateChanged.connect(self._onCheckBoxChange) self.regexpCheckBox = QCheckBox(self) self.regexpCheckBox.setText("Regexp") self.regexpCheckBox.setFocusPolicy(Qt.NoFocus) self.regexpCheckBox.setEnabled(False) self.regexpCheckBox.stateChanged.connect(self._onCheckBoxChange) self.findtextCombo.lineEdit().returnPressed.connect(self.__findByReturnPressed) self._skip = False return def keyPressEvent(self, event): " Handles the ESC key for the search bar " if event.key() == Qt.Key_Escape: self._searchSupport.clearStartPositions() event.accept() self.hide() activeWindow = self.editorsManager.currentWidget() if activeWindow: activeWindow.setFocus() return def __onTabClosed(self, uuid): " Triggered when a tab is closed " self._searchSupport.delete(uuid) return def setFocus(self): " Overridded setFocus " self.findtextCombo.lineEdit().selectAll() self.findtextCombo.setFocus() return def show(self, text=""): " Overridden show() method " self._skip = True self.findtextCombo.clear() self.findtextCombo.addItems(self.findHistory) self.findtextCombo.setEditText(text) self.findtextCombo.lineEdit().selectAll() self.regexpCheckBox.setChecked(False) self.findtextCombo.setFocus() self._findBackward = False self._skip = False QWidget.show(self) self.activateWindow() self._performSearch(True) return def startHiddenSearch(self, text): " Initiates search without activating the widget " self._skip = True self.findtextCombo.clear() self.findtextCombo.addItems(self.findHistory) self.findtextCombo.setEditText(text) self.findtextCombo.lineEdit().selectAll() self.regexpCheckBox.setChecked(False) self._findBackward = False self._skip = False self._performSearch(True) return def updateStatus(self): " Triggered when the current tab is changed " # Memorize the current environment self._currentWidget = self.editorsManager.currentWidget() self._isTextEditor = self._currentWidget.getType() in [ MainWindowTabWidgetBase.PlainTextEditor, MainWindowTabWidgetBase.VCSAnnotateViewer, ] if self._isTextEditor: self._editor = self._currentWidget.getEditor() self._editorUUID = self._currentWidget.getUUID() else: self._editor = None self._editorUUID = "" self.findtextCombo.setEnabled(self._isTextEditor) textAvailable = self.findtextCombo.currentText() != "" self.findPrevButton.setEnabled(self._isTextEditor and textAvailable) self.findNextButton.setEnabled(self._isTextEditor and textAvailable) self.caseCheckBox.setEnabled(self._isTextEditor) self.wordCheckBox.setEnabled(self._isTextEditor) self.regexpCheckBox.setEnabled(self._isTextEditor) return def _resetHighlightOtherEditors(self, uuid): " Resets all the highlights in other editors except of the given " searchAttributes = None if self._searchSupport.hasEditor(uuid): searchAttributes = self._searchSupport.get(uuid) for key in self._searchSupport.editorSearchAttributes: if key == uuid: continue widget = self.editorsManager.getWidgetByUUID(key) if widget is None: continue editor = widget.getEditor() editor.clearSearchIndicators() # Clear what is memorized about the other editors self._searchSupport.editorSearchAttributes = {} if searchAttributes is not None: self._searchSupport.add(uuid, searchAttributes) return def _onCheckBoxChange(self, newState): " Triggered when a search check box state is changed " if self._skip: return self._resetHighlightOtherEditors(self._editorUUID) self._performSearch(False) return def _onEditTextChanged(self, text): " Triggered when the search text has been changed " if self._skip: return self._resetHighlightOtherEditors(self._editorUUID) self._performSearch(False) return def _performSearch(self, fromScratch): " Performs the incremental search " if not self._isTextEditor: return # Memorize the search arguments text = self.findtextCombo.currentText() isRegexp = self.regexpCheckBox.isChecked() isCase = self.caseCheckBox.isChecked() isWord = self.wordCheckBox.isChecked() status = text != "" self.findNextButton.setEnabled(status) self.findPrevButton.setEnabled(status) if fromScratch: self._searchSupport.delete(self._editorUUID) self._initialiseSearchAttributes(self._editorUUID) searchAttributes = self._searchSupport.get(self._editorUUID) if not fromScratch: # We've been searching here already if text == "": # Remove the highlight and scroll back self._editor.clearAllIndicators(self._editor.searchIndicator) self._editor.clearAllIndicators(self._editor.matchIndicator) self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos) self._editor.ensureLineVisible(searchAttributes.firstLine) searchAttributes.match = [-1, -1, -1] self.incSearchDone.emit(False) return matchTarget = self._editor.highlightMatch( text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord ) searchAttributes.match = matchTarget if matchTarget != [-1, -1, -1]: # Select the match starting from the end. This will move the # cursor to the beginnig of the match. tgtPos = self._editor.positionFromLineIndex(matchTarget[0], matchTarget[1]) eLine, ePos = self._editor.lineIndexFromPosition(tgtPos + matchTarget[2]) self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1]) self._editor.ensureLineVisible(matchTarget[0]) self.incSearchDone.emit(True) else: # Nothing is found, so scroll back to the original self._editor.setCursorPosition(searchAttributes.line, searchAttributes.pos) self._editor.ensureLineVisible(searchAttributes.firstLine) self.incSearchDone.emit(False) return # Brand new editor to search in if text == "": self.incSearchDone.emit(False) return matchTarget = self._editor.highlightMatch( text, searchAttributes.line, searchAttributes.pos, isRegexp, isCase, isWord ) searchAttributes.match = matchTarget self._searchSupport.add(self._editorUUID, searchAttributes) if matchTarget != [-1, -1, -1]: # Select the match starting from the end. This will move the # cursor to the beginnig of the match. tgtPos = self._editor.positionFromLineIndex(matchTarget[0], matchTarget[1]) eLine, ePos = self._editor.lineIndexFromPosition(tgtPos + matchTarget[2]) self._editor.setSelection(eLine, ePos, matchTarget[0], matchTarget[1]) self._editor.ensureLineVisible(matchTarget[0]) self.incSearchDone.emit(True) return self.incSearchDone.emit(False) return def _initialiseSearchAttributes(self, uuid): " Creates a record if none existed " if self._searchSupport.hasEditor(uuid): return searchAttributes = SearchAttr() searchAttributes.line = self._currentWidget.getLine() searchAttributes.pos = self._currentWidget.getPos() searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(uuid, searchAttributes) return def _advanceMatchIndicator(self, uuid, newLine, newPos, newLength): " Advances the current match indicator for the given editor " if not self._searchSupport.hasEditor(uuid): return searchAttributes = self._searchSupport.get(uuid) match = searchAttributes.match widget = self.editorsManager.getWidgetByUUID(uuid) if widget is None: return editor = widget.getEditor() # Replace the old highlight if searchAttributes.match != [-1, -1, -1]: tgtPos = editor.positionFromLineIndex(match[0], match[1]) editor.clearIndicatorRange(editor.matchIndicator, tgtPos, match[2]) editor.setIndicatorRange(editor.searchIndicator, tgtPos, match[2]) # Memorise new target searchAttributes.match = [newLine, newPos, newLength] self._searchSupport.add(uuid, searchAttributes) # Update the new highlight tgtPos = editor.positionFromLineIndex(newLine, newPos) editor.clearIndicatorRange(editor.searchIndicator, tgtPos, newLength) editor.setIndicatorRange(editor.matchIndicator, tgtPos, newLength) # Select the match from end to the start - this will move the # cursor to the first symbol of the match eLine, ePos = editor.lineIndexFromPosition(tgtPos + newLength) editor.setSelection(eLine, ePos, newLine, newPos) # Move the cursor to the new match editor.ensureLineVisible(newLine) return def onNext(self, clearSBMessage=True): " Triggered when the find next is clicked " if not self.onPrevNext(): return self._findBackward = False if not self.__findNextPrev(clearSBMessage): GlobalData().mainWindow.showStatusBarMessage( "The '" + self.findtextCombo.currentText() + "' was not found.", 0 ) self.incSearchDone.emit(False) else: self.incSearchDone.emit(True) return def onPrev(self, clearSBMessage=True): " Triggered when the find prev is clicked " if not self.onPrevNext(): return self._findBackward = True if not self.__findNextPrev(clearSBMessage): GlobalData().mainWindow.showStatusBarMessage( "The '" + self.findtextCombo.currentText() + "' was not found.", 0 ) self.incSearchDone.emit(False) else: self.incSearchDone.emit(True) return def onPrevNext(self): """ Checks prerequisites, saves the history and returns True if the search should be done """ txt = self.findtextCombo.currentText() if txt == "": return False currentWidget = self.editorsManager.currentWidget() if currentWidget.getType() not in [ MainWindowTabWidgetBase.PlainTextEditor, MainWindowTabWidgetBase.VCSAnnotateViewer, ]: return False return True def __findByReturnPressed(self): " Triggered when 'Enter' or 'Return' is clicked " if self._findBackward: self.onPrev() else: self.onNext() return def __findNextPrev(self, clearSBMessage=True): " Finds the next occurrence of the search text " if not self._isTextEditor: return False # Identify the search start point startLine = self._currentWidget.getLine() startPos = self._currentWidget.getPos() if self._searchSupport.hasEditor(self._editorUUID): searchAttributes = self._searchSupport.get(self._editorUUID) if startLine == searchAttributes.match[0] and startPos == searchAttributes.match[1]: # The cursor is on the current match, i.e. the user did not # put the focus into the editor and did not move it if not self._findBackward: # The match[ 2 ] gives the length in bytes, not in chars # which could be national i.e. multibytes. So calc the # right length in chars... pos = self._editor.positionFromLineIndex(startLine, startPos) adjustment = len(self._editor.stringAt(pos, searchAttributes.match[2])) startPos = startPos + adjustment else: # The cursor is not at the same position as the last match, # i.e. the user moved it some way # Update the search attributes as if a new search is started searchAttributes.line = startLine searchAttributes.pos = startPos searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) else: # There were no search in this editor searchAttributes = SearchAttr() searchAttributes.line = startLine searchAttributes.pos = startPos searchAttributes.firstLine = self._editor.firstVisibleLine() searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) # Here: start point has been identified if self.__searchFrom(startLine, startPos, clearSBMessage): # Something new has been found - change the start pos searchAttributes = self._searchSupport.get(self._editorUUID) searchAttributes.line = self._currentWidget.getLine() searchAttributes.pos = self._currentWidget.getPos() searchAttributes.firstLine = self._editor.firstVisibleLine() self._searchSupport.add(self._editorUUID, searchAttributes) return True return False def __searchFrom(self, startLine, startPos, clearSBMessage=True): " Searches starting from the given position " # Memorize the search arguments text = self.findtextCombo.currentText() isRegexp = self.regexpCheckBox.isChecked() isCase = self.caseCheckBox.isChecked() isWord = self.wordCheckBox.isChecked() if not self._findBackward: # Search forward self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1) if len(targets) == 0: GlobalData().mainWindow.showStatusBarMessage( "Reached the end of the document. " "Searching from the beginning...", 0 ) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos) if len(targets) == 0: searchAttributes = self._searchSupport.get(self._editorUUID) searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) return False # Nothing has matched else: if clearSBMessage: # Hide the 'reached the end of ...' message GlobalData().mainWindow.clearStatusBarMessage(0) # Move the highlight and the cursor to the new match and # memorize a new match self._advanceMatchIndicator(self._editorUUID, targets[0][0], targets[0][1], targets[0][2]) return True # Search backward self._editor.highlightMatch(text, startLine, startPos, isRegexp, isCase, isWord, False, False) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, 0, 0, startLine, startPos) if len(targets) == 0: GlobalData().mainWindow.showStatusBarMessage( "Reached the beginning of the document. " "Searching from the end...", 0 ) targets = self._editor.getTargets(text, isRegexp, isCase, isWord, startLine, startPos, -1, -1) if len(targets) == 0: searchAttributes = self._searchSupport.get(self._editorUUID) searchAttributes.match = [-1, -1, -1] self._searchSupport.add(self._editorUUID, searchAttributes) return False # Nothing has matched else: if clearSBMessage: # Hide the 'reached the beginning of ...' message GlobalData().mainWindow.clearStatusBarMessage(0) # Move the highlight and the cursor to the new match and # memorize a new match index = len(targets) - 1 self._advanceMatchIndicator(self._editorUUID, targets[index][0], targets[index][1], targets[index][2]) return True def _addToHistory(self, combo, history, text): " Adds the item to the history. Returns true if need to add. " text = str(text) changes = False if text in history: if history[0] != text: changes = True history.remove(text) history.insert(0, text) else: changes = True history.insert(0, text) if len(history) > self.maxHistory: changes = True history = history[: self.maxHistory] self._skip = True combo.clear() combo.addItems(history) self._skip = False return changes def getLastSearchString(self): " Provides the string which was searched last time " return self.findtextCombo.currentText()
class mpl_widget(QWidget): def __init__(self, parent=None, mainWidget=None): self._SELECTEDCELLS = list() # container for instances of selected cells, so we can delete them when we want self._SELECTEDCELLS_IJ = list() # container for coords of selected cells, so we can delete them when we want self._SELECTEDCELLLINES = list() # container for instances of selected cells, so we can delete them when we want self._GRIDLINES = None QWidget.__init__(self, parent) self.mainWidget = mainWidget self.create_main_frame() self.mpl_menu = mpl_menu(self) self.shift_is_held = False #self.connect(self.mpl_menu, QtCore.SIGNAL('mySignal'), self.mySlot) #print 'my parent is:', parent self.clear_selection() self.init_tooltips() def init_tooltips(self): self.canvas.setToolTip('If 2D plot => RMB click toggles menu <br> - RMB click selects cell <br> - selected cells are drawn with black border') self.grid_cb.setToolTip('If 2D plot => show computational grid <br> If 1D plot => show normal gridlines') self.cbar_button.setToolTip('If 2D plot => controls the color range. <br> Note: <br> - pressing UP and DOWN arrows cycles through colormaps <br> - dragging colorbar with RMB scales the color-range <br> - dragging colorbar with LMB shifts the color-range') self.mpl_toolbar.setToolTip('Shows coordinates (i,j, lat,lon) and data-value(z) under the cursor. <br> if you see <i>>>></i> coordinates are not visible. Enlarge the window') def create_main_frame(self): self.fig = Figure(dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.setFocusPolicy( Qt.ClickFocus ) self.canvas.setFocus() self.mpl_toolbar = myNavigationToolbar(self.canvas, self) self.canvas.mpl_connect('button_press_event', self.on_click) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.canvas.mpl_connect('key_release_event', self.on_key_release) #self.canvas.mpl_connect('button_press_event', self.disable_clicks) self.cbar_button = QPushButton("Color Range") self.cbar_button.setFocusPolicy( Qt.NoFocus ) self.grid_cb = QCheckBox("Show Grid") self.grid_cb.setFocusPolicy( Qt.NoFocus ) self.grid_cb.stateChanged.connect(self.showGrid) vbox = QVBoxLayout() hbox = QHBoxLayout() vbox.addWidget(self.canvas) # the matplotlib canvas hbox.addWidget(self.mpl_toolbar) hbox.addWidget(self.cbar_button) hbox.addWidget(self.grid_cb) vbox.addLayout(hbox) self.setLayout(vbox) def on_click(self, event): if event.inaxes != self.get_axes()[0]: return #if self.get_axes()[0].format_coord(event.x, event.y) == 'outside data area': return if self.allow_menu(): self.allow_popup_menu = True if self.shift_is_held: self.allow_popup_menu = False point = [int(event.xdata + .5), int(event.ydata + .5)] #print '>>>', point, '\t currently {0} selected'.format(len(self._SELECTEDCELLS)) if event.button == 3 : #if RMB is clicked # working with dialog for transect! if self.mainWidget.transect_dlg: if self.mainWidget.transect_dlg.toogle_show_after_selected_cell: realx, realy = self.get_real_xy(event.xdata, event.ydata, self.mainWidget.detect_variable_dimensions()) realpoint = [realy, realx] #print 'real xy:', realpoint if self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 1: # select point 1 self.allow_popup_menu = False self.mainWidget.transect_dlg.data.set_p1(realpoint) elif self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 2: # select point 2 self.allow_popup_menu = False self.mainWidget.transect_dlg.data.set_p2(realpoint) self.mainWidget.transect_dlg.update() self.mainWidget.transect_dlg.show() # working with dialog for flux! if self.mainWidget.flux_dlg: if self.mainWidget.flux_dlg.toogle_show_after_selected_cell: if self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 1: # select point 1 self.allow_popup_menu = False self.mainWidget.flux_dlg.data.set_p1(point) elif self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 2: # select point 2 self.allow_popup_menu = False self.mainWidget.flux_dlg.data.set_p2(point) self.mainWidget.flux_dlg.update() self.mainWidget.flux_dlg.show() if len(self._SELECTEDCELLS) == 0: # if no cell is selected self.add_selected_cell(point) else: # if some cells are already selected if self.mpl_menu.allow_rmb_select_cells() or self.shift_is_held: # check if this point is already selected: already_selected = False for p in self._SELECTEDCELLS_IJ: if (point[0] == p[0]) and (point[1] == p[1]): already_selected = True print 'cell already selected... is not added' if not already_selected: self.add_selected_cell(point) else: pass #self.clear_selection() #self.add_selected_cell(point) def cells_selected(self): if self._SELECTEDCELLS: return len(self._SELECTEDCELLS) else: return False def add_selected_cell(self, point): ''' point = [i, j]''' print 'selected cell:', point[0], point[1] c = self.draw_picked_cell(point) self._SELECTEDCELLS.append(c) self._SELECTEDCELLS_IJ.append(point) def get_selected_cells_ij(self): return self._SELECTEDCELLS_IJ def clear_selection(self): ''' delete all graphical objects of selected cells redraw canvas ''' print 'clearing stuff' if len(self._SELECTEDCELLLINES) > 0: for line in self._SELECTEDCELLLINES: l = line.pop(0) l.remove() del l del self._SELECTEDCELLLINES[:] #print 'cells ---- before:', len(self._SELECTEDCELLS) if len(self._SELECTEDCELLS) > 0: for cell in self._SELECTEDCELLS: for line in cell: l = line.pop(0) l.remove() del l del self._SELECTEDCELLS[:] #print 'cells ---- left:', len(self._SELECTEDCELLS) #print 'cells-coords ----' #print len(self._SELECTEDCELLS_IJ) if self._SELECTEDCELLS_IJ: for cellcoords in self._SELECTEDCELLS_IJ: #cc = cellcoords.pop(0) #cellcoords.remove() del cellcoords del self._SELECTEDCELLS_IJ[:] #print 'cells ---- left,', len(self._SELECTEDCELLS_IJ) if len(self._SELECTEDCELLS) != 0: raise ValueError('List "self._SELECTEDCELLS" was not flushed') if len(self._SELECTEDCELLLINES) != 0: raise ValueError('List "self._SELECTEDCELLLINES" was not flushed') if len(self._SELECTEDCELLS_IJ) != 0: raise ValueError('List "self._SELECTEDCELLLINES" was not flushed') # update plot self.canvas.draw() #print 'finishing clear: cells left', len(self._SELECTEDCELLS) def showGrid(self, state): if self.fig.axes: current_plot = self.mainWidget.get_plotType() current_plot2D = self.mainWidget.get_plotType_for_timeseries() if state == Qt.Checked: if current_plot == '1D' or (current_plot2D =="2DZT"): self.fig.axes[0].grid(True) elif current_plot == '2D' and (not current_plot2D =="2DZT"): self.draw_pixel_grid(True) else: if current_plot == '1D' or (current_plot2D =="2DZT"): self.fig.axes[0].grid(False) elif current_plot == '2D' and (not current_plot2D =="2DZT"): self.draw_pixel_grid(False) self.canvas.draw() def draw_picked_cell(self, point): x = point[0] y = point[1] ''' approach drawing a patch... not working cell_bnd = patches.Rectangle((x-.5, y-.5), 1, 1, fill=False, edgecolor="black", hatch=None, linewidth=1.) cell_instance = self.fig.axes[0].add_patch(cell_bnd) ''' b_line = [(x-.5, x+.5), (y-.5, y-.5)] r_line = [(x+.5, x+.5), (y-.5, y+.5)] t_line = [(x-.5, x+.5), (y+.5, y+.5)] l_line = [(x-.5, x-.5), (y-.5, y+.5)] cell = [b_line, r_line, t_line, l_line] for i, l in enumerate(cell): ll = self.fig.axes[0].plot(l[0], l[1], 'k-', lw=.8) cell[i] = ll # overwriting current Line2D object with object binded to an axes #self._SELECTEDCELLS.append(cell) # collecting reference to this cell to be able to delete it #self._SELECTEDCELLS_IJ.append(point) # collecting reference to this cell to be able to delete it self.canvas.draw() return cell def draw_line(self, point1, point2): line = [(point1[0], point2[0]), (point1[1], point2[1])] l = self.fig.axes[0].plot(line[0], line[1], 'k-', lw=2) return l def draw_pixel_grid(self, enable=True): if enable: dx = 1 dy = 1 x0 = -.5 y0 = -.5 if self.mainWidget.get_plotType_for_timeseries() == '2DXY': nx = self.mainWidget.get_nX() ny = self.mainWidget.get_nY() elif self.mainWidget.get_plotType_for_timeseries() == '2DZY': nx = self.mainWidget.get_nY() ny = self.mainWidget.get_nZ() elif self.mainWidget.get_plotType_for_timeseries() == '2DZX': nx = self.mainWidget.get_nX() ny = self.mainWidget.get_nZ() self._GRIDLINES = list() for n_hline in np.arange(ny+1): hline = [(x0, x0+nx), (y0+n_hline, y0+n_hline)] l = self.fig.axes[0].plot(hline[0], hline[1], 'k-', lw=.2) self._GRIDLINES.append(l) # collecting reference to this line to be able to delete it for n_vline in np.arange(nx+1): vline = [(x0+n_vline, x0+n_vline), (y0, y0+ny)] l = self.fig.axes[0].plot(vline[0], vline[1], 'k-', lw=.2) self._GRIDLINES.append(l) # collecting reference to this line to be able to delete it if not enable: #print 'deleting lines...' if self._GRIDLINES: # if lines were created #print 'lines are here...' for line in self._GRIDLINES: #print line l = line.pop(0) l.remove() del l self.fig.canvas.draw() def on_key_press(self, event): #print 'key pressed:', event.key if event.key == 'shift': self.shift_is_held = True def on_key_release(self, event): #print 'key released:', event.key if event.key == 'shift': self.shift_is_held = False elif event.key == 'escape': self.clear_selection() def change_coordinate_formatter(self, ax, data2d, bruteforce_flag=None, bruteforce_dims=None): ''' see http://stackoverflow.com/questions/14754931/matplotlib-values-under-cursor ''' numrows, numcols = data2d.shape bruteforce_mode_on = False bruteforce_mode_on = (bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2]) def format_coord(x, y): col = int(x+0.5) row = int(y+0.5) if not bruteforce_mode_on: if col >= 0 and col < numcols and row >= 0 and row < numrows: #z = data2d[row, col] # sice we have artificially reversed y-coordinate axes, now reverse data! # numrows-1, because if nrows=10 => row=[0:9] z = data2d[numrows-1-row, col] #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z) return 'i=%d j=%d z=%.6f' % (col, row, z) else: #return 'x=%1.4f, y=%1.4f' % (x, y) return 'outside data area' elif bruteforce_flag == '2DXY' and bruteforce_dims[-1] and bruteforce_dims[-2]: ''' our extend in X=[-0.5:numcols-0.5], Y=[-0.5:numrows-0.5], because col,row is cell center! ''' if col >= 0 and col < numcols and row >= 0 and row < numrows: #z = data2d[row, col] # sice we have artificially reversed y-coordinate axes, now reverse data! # numrows-1, because if nrows=10 => row=[0:9] z = data2d[numrows-1-row, col] real_x, real_y = self.get_real_xy(x, y, bruteforce_dims) #return 'x=%1.1f y=%1.1f z=%1.6f' % (x, y, z) #return 'i=%d j=%d z=%.3f x=%.4f y=%.4f' % (col, row, z, real_x, real_y) return 'i=%d j=%d z=%.3f, %s=%.2f %s=%.2f' % ( col, row, z, bruteforce_dims[-1], real_x, bruteforce_dims[-2], real_y) else: #return 'x=%1.4f, y=%1.4f' % (x, y) return 'outside data area' else: raise ValueError('bruteforce_flag can be $None$ or $"2DXY"$. Passed %s' % bruteforce_flag) ax.format_coord = format_coord def allow_menu(self): allow = False #print "self.mainWidget.get_plotType():", self.mainWidget.get_plotType() #print "self.mainWidget.get_plotType_for_timeseries():", self.mainWidget.get_plotType_for_timeseries() if self.mainWidget.get_plotType() == "2D" and not self.mainWidget.get_plotType_for_timeseries() == "2DZT": allow = True return allow def get_real_xy(self, i, j, dimension_list): ''' functions returns values of x,y based on passed indexes i, j ''' if any(dimension_list[-2:-1]) is None: print 'Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)' raise ValueError('Dimensions X,Y of current variable are not specified (variables that have same name as dimensions not found)') nc = self.mainWidget.get_selected_ncfile_instance() try: x_var = nc.variables[dimension_list[-1]] y_var = nc.variables[dimension_list[-2]] except: print ('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2])) raise ValueError('Failed to load variables: {0}, {1}'.format(dimension_list[-1], dimension_list[-2])) x_ratio = (x_var[-1]-x_var[0])/(len(x_var)-1) y_ratio = (y_var[-1]-y_var[0])/(len(y_var)-1) #x[i] = x_var[0]+x_ratio*i #y[j] = y_var[0]+y_ratio*j x = x_var[0] + x_ratio*i y = y_var[0] + y_ratio*j nc.close() return (x, y) def get_axes(self): return self.fig.get_axes() def fast_redraw(self, artist): background = [self.canvas.copy_from_bbox(self.get_axes()[0].bbox)] self.get_axes()[0].draw_artist(artist) self.canvas.restore_region(background) self.canvas.blit(self.get_axes()[0].bbox) self.canvas.update() self.canvas.flush_events()