def start(): #Init Qt Application app = QApplication(sys.argv) #Set application organization, name and version QCoreApplication.setOrganizationName('lol-server-status') QCoreApplication.setApplicationName(__prj__) QCoreApplication.setApplicationVersion(__version__) #Set icon for application app.setWindowIcon(QIcon(IMAGES['icon_256'])) #Codec for QString QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Add StyleSheet with open(STYLES, 'r') as f: style = f.read() app.setStyleSheet(style) f.close() #Run user interface window = mainWindow() window.show() sys.exit(app.exec_())
def getEncodings(): """Returns a list of available encodings static.""" return [ unicode(QTextCodec.codecForMib(mib).name()) for mib in QTextCodec.availableMibs() ]
def getEncodings(): """Return a list of available encodings.""" names = [ unicode(QTextCodec.codecForMib(mib).name()) for mib in QTextCodec.availableMibs() ] return names
def __init__(self, iface, parent=None, featuresId=None, layer=None): """Constructor.""" QDialog.__init__(self) self.setupUi(self) self.s = QSettings() self.plugin_path = os.path.dirname(os.path.realpath(__file__)) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) Gui.loadLatin1Encoding() self.iface = iface self.canvas = self.iface.mapCanvas() self.parent = parent #Orientation from image self.yaw = math.pi self.bearing = None self.layer = layer self.featuresId = featuresId #Restore Previous size self.RestoreSize() #defaults self.actualPointDx = None self.actualPointSx = None self.actualPointOrientation = None self.selected_features = qgsutils.getToFeature(self.canvas, self.layer, self.featuresId) #Get image path self.current_image = self.GetImage() QtGui.qApp.processEvents() #Creamos el visor self.CreateViewer() QtGui.qApp.processEvents() #Check if image exist if os.path.exists(self.current_image) is False: qgsutils.showUserAndLogMessage(self, u"Information: ", u"There is no associated image.", QgsMessageBar.INFO) self.ChangeUrlViewer(config.DEFAULT_EMPTY) self.setPosition() return #Set RubberBand self.setOrientation() self.setPosition() QtGui.qApp.processEvents() #Copy file to local server self.CopyFile(self.current_image) QtGui.qApp.processEvents()
def main(args): app = QApplication(args) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) initProperty() AppProperty.MainWin = Window("login.html", 280, 600) AppProperty.MainWin.show() createTray() app.exec_()
def main(args): app = QApplication(args) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) initProperty() AppProperty.MainWin = Window("login.html",280,600) AppProperty.MainWin.show() createTray() app.exec_()
def main(): # 每一个PyQt4程序都必须创建一个QApplication对象[QtGui.QApplication(sys.argv)] app = QApplication(sys.argv) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("GBK")) initProperty() AppProperty.MainWin = Window("main.html",1300,600) AppProperty.MainWin.show() createTray() sys.exit(app.exec_())
def btn_calculate(self): if self.area_admin.isChecked(): if not self.area_admin_0.currentText(): QtGui.QMessageBox.critical( None, self.tr("Error"), self.tr("Choose a first level administrative boundary."), None) return False self.button_calculate.setEnabled(False) geojson = self.load_admin_polys() self.button_calculate.setEnabled(True) if not geojson: QtGui.QMessageBox.critical( None, self.tr("Error"), self.tr("Unable to load administrative boundaries."), None) return False else: if not self.area_fromfile_file.text(): QtGui.QMessageBox.critical( None, self.tr("Error"), self.tr("Choose a file to define the area of interest."), None) return False layer = QgsVectorLayer(self.area_fromfile_file.text(), 'calculation boundary', 'ogr') if not layer.isValid(): QtGui.QMessageBox.critical( None, self.tr("Error"), self.tr("Unable to read area file."), None) return False log('Loaded layer: {}'.format( layer.dataProvider().dataSourceUri())) #TODO: Fix this kludge for f in layer.getFeatures(): aoi = f.geometry() break crs_source = layer.crs() crs_dest = QgsCoordinateReferenceSystem(4326) aoi.transform(QgsCoordinateTransform(crs_source, crs_dest)) geojson = json.loads(aoi.exportToGeoJSON()) # Calculate bounding box of input polygon and then convert back to # geojson fields = QgsJSONUtils.stringToFields(json.dumps(geojson), QTextCodec.codecForName('UTF8')) features = QgsJSONUtils.stringToFeatureList( json.dumps(geojson), fields, QTextCodec.codecForName('UTF8')) if len(features) > 1: log("Found {} features in geojson - using first feature only.". format(len(features))) # Make a copy of this geometry self.aoi = QgsGeometry(features[0].geometry()) self.bbox = json.loads( QgsGeometry.fromRect(self.aoi.boundingBox()).exportToGeoJSON()) return True
def _get_source(self, current_frame): # TODO: Automatically detect charset from metadata. # qwebframe.metaData() seems poor. source = current_frame.toHtml() if self.charset == "euc-kr": # For euc-kr QTextCodec.setCodecForCStrings(QTextCodec.codecForName("EUC-KR")) self.source = unicode(source, 'euc-kr') else: self.source = unicode(source)
def restore(self): if not self._patched: raise Exception('encoding not patched') if self._origenvencoding is not None: os.environ['HGENCODING'] = self._origenvencoding encodingmod.encoding = self._origencoding encodingmod.fallbackencoding = self._origfallbackencoding hglib._encoding = self._orighglibencoding hglib._fallbackencoding = self._orighglibfallbackencoding QTextCodec.setCodecForLocale(self._origqtextcodec) self._patched = False
def simpleAppStartup(argv, appinfo, mwFactory, kqOptions = [], quitOnLastWindowClosed = True, raiseIt = True): """ Function to start up an application that doesn't need a specialized start up. This function is used by all of eric4's helper programs. @param argv list of commandline parameters (list of strings) @param appinfo dictionary describing the application @param mwFactory factory function generating the main widget. This function must accept the following parameter. <dl> <dt>argv</dt> <dd>list of commandline parameters (list of strings)</dd> </dl> @keyparam kqOptions list of acceptable command line options. This is only used, if the application is running under KDE and pyKDE can be loaded successfully. @keyparam quitOnLastWindowClosed flag indicating to quit the application, if the last window was closed (boolean) @keyparam raiseIt flag indicating to raise the generated application window (boolean) """ ddindex = handleArgs(argv, appinfo) app = KQApplication(argv, kqOptions) app.setQuitOnLastWindowClosed(quitOnLastWindowClosed) try: sys.setappdefaultencoding(str(Preferences.getSystem("StringEncoding"))) except AttributeError: pass setLibraryPaths() initializeResourceSearchPath() QApplication.setWindowIcon(UI.PixmapCache.getIcon("eric.png")) qt4TransDir = Preferences.getQt4TranslationsDir() if not qt4TransDir: qt4TransDir = QLibraryInfo.location(QLibraryInfo.TranslationsPath) loadTranslators(qt4TransDir, app) QTextCodec.setCodecForCStrings(\ QTextCodec.codecForName(str(Preferences.getSystem("StringEncoding"))) ) w = mwFactory(argv) if quitOnLastWindowClosed: app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) w.show() if raiseIt: w.raise_() return app.exec_()
def btn_calculate(self): if self.area_admin.isChecked(): if not self.area_admin_0.currentText(): QtGui.QMessageBox.critical(None, self.tr("Error"), self.tr("Choose a first level administrative boundary."), None) return False self.button_calculate.setEnabled(False) geojson = self.load_admin_polys() self.button_calculate.setEnabled(True) if not geojson: QtGui.QMessageBox.critical(None, self.tr("Error"), self.tr("Unable to load administrative boundaries."), None) return False elif self.area_fromfile.isChecked(): if not self.area_fromfile_file.text(): QtGui.QMessageBox.critical(None, self.tr("Error"), self.tr("Choose a file to define the area of interest."), None) return False layer = QgsVectorLayer(self.area_fromfile_file.text(), 'calculation boundary', 'ogr') crs_source = layer.crs() crs_dest = QgsCoordinateReferenceSystem(4326) extent = layer.extent() extent_transformed = QgsCoordinateTransform(crs_source, crs_dest).transform(extent) geojson = json.loads(QgsGeometry.fromRect(extent_transformed).exportToGeoJSON()) else: # Area from point if not self.point_x.text() and not self.point_y.text(): QtGui.QMessageBox.critical(None, self.tr("Error"), self.tr("Choose a point to define the area of interest."), None) return False point = QgsPoint(float(self.point_x.text()), float(self.point_y.text())) crs_source = QgsCoordinateReferenceSystem(self.canvas.mapRenderer().destinationCrs().authid()) crs_dest = QgsCoordinateReferenceSystem(4326) point = QgsCoordinateTransform(crs_source, crs_dest).transform(point) geojson = json.loads(QgsGeometry.fromPoint(point).exportToGeoJSON()) self.close() # Calculate bounding box of input polygon and then convert back to # geojson fields = QgsJSONUtils.stringToFields(json.dumps(geojson), QTextCodec.codecForName('UTF8')) features = QgsJSONUtils.stringToFeatureList(json.dumps(geojson), fields, QTextCodec.codecForName('UTF8')) if len(features) > 1: log("Found {} features in geojson - using first feature only.".format(len(features))) #self.bbox = json.loads(features[0].geometry().convexHull().exportToGeoJSON()) self.bbox = json.loads(QgsGeometry.fromRect(features[0].geometry().boundingBox()).exportToGeoJSON()) log("Calculating timeseries for: {}.".format(self.bbox)) ndvi_dataset = self.datasets['NDVI'][self.dataset_ndvi.currentText()]['GEE Dataset'] self.calculate_timeseries(self.bbox, ndvi_dataset)
def initShape(self): self.hbox = QHBoxLayout() self.hbox.setContentsMargins(0, 0, 0, 0) self.listWidget = QListWidget() self.listWidget.setSortingEnabled(True) for codec in QTextCodec.availableCodecs(): self.listWidget.addItem(str(codec)) item = self.listWidget.findItems('UTF-8', Qt.MatchExactly)[0] self.listWidget.setCurrentItem(item) self.listWidget.scrollToItem(item) textAreaWidget = QWidget() self.hbox.addWidget(self.listWidget) self.connect(self.listWidget, SIGNAL("itemSelectionChanged()"), self.codecChanged) self.scroll = Scroll(self) self.text = TextEdit(self) self.hbox.addWidget(self.text) self.hbox.addWidget(self.scroll) textAreaWidget.setLayout(self.hbox) self.addWidget(self.listWidget) self.addWidget(textAreaWidget) self.setStretchFactor(0, 0) self.setStretchFactor(1, 1)
def __init__(self, parent = None): """ Constructor """ QTextCodec.setCodecForCStrings(QTextCodec.codecForName('gbk')) QMainWindow.__init__(self, parent) self.setupUi(self) self.caseDir = '' self.selectedCaseList = [] self.caselist = [] self.treeWidget_caseTree.itemChanged.connect(self.treehandleChanged) #设置table的列宽 self.tableWidget.setColumnWidth(0,40) self.tableWidget.setColumnWidth(1,180) self.tableWidget.setColumnWidth(2,70) self.tableWidget_caseList.setColumnWidth(0,150)
def writeVectorLayerToShape(vlayer, outputPath, encoding): mCodec = QTextCodec.codecForName(encoding) if not mCodec: return False #Here we should check that the output path is valid QgsVectorFileWriter.writeAsVectorFormat(vlayer, outputPath, encoding, vlayer.dataProvider().crs(), "ESRI Shapefile", False) return True
def start(): app = QApplication(sys.argv) QCoreApplication.setApplicationName(__prj__) QCoreApplication.setApplicationVersion(__version__) #Set Application icon app.setWindowIcon(QIcon(IMAGES['minebackup_icon'])) #Codec for QString QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Create configuration configuration.config() minebackup = main_window() minebackup.show() sys.exit(app.exec_())
def main(): qapp = QApplication(sys.argv) app.g_pwd = os.getcwd() print app.g_pwd tc = QTextCodec.codecForName('utf-8') QTextCodec.setCodecForCStrings(tc) QTextCodec.setCodecForLocale(tc) QTextCodec.setCodecForTr(tc) #遍历目录 tmpdirs = os.listdir(app.g_pwd + os.sep + 'templates') for tmpdir in tmpdirs: currentdir = app.g_pwd + os.sep + 'templates' + os.sep + tmpdir if os.path.isdir(currentdir) and os.path.exists(currentdir + os.sep + 'config.json'): app.g_templates.append(tmpdir) #检查 ALLONEDIR 和 QTDIR if os.getenv('ALLONEDIR', '') == '' or os.getenv('QTDIR', '') == '': QMessageBox.warning(None, '提示信息', '使用组件设计工具前,请先设置 ALLONEDIR 和 QTDIR 的系统环境变量!') return m = mainwindow.mainwindow() m.show() qapp.setStyleSheet(styleSheet) qapp.exec_()
def patch(self): if self._patched: raise Exception('encoding already patched') self._origenvencoding = os.environ.get('HGENCODING') self._origencoding = encodingmod.encoding self._origfallbackencoding = encodingmod.fallbackencoding self._orighglibencoding = hglib._encoding self._orighglibfallbackencoding = hglib._fallbackencoding self._origqtextcodec = QTextCodec.codecForLocale() os.environ['HGENCODING'] = self._newencoding encodingmod.encoding = self._newencoding encodingmod.fallbackencoding = self._newfallbackencoding hglib._encoding = self._newencoding hglib._fallbackencoding = self._newfallbackencoding QTextCodec.setCodecForLocale( QTextCodec.codecForName(self._newencoding)) self._patched = True
def main(): app = QApplication(sys.argv) textCodec = QTextCodec.codecForName('utf-8') QTextCodec.setCodecForCStrings(textCodec) QTextCodec.setCodecForLocale(textCodec) QTextCodec.setCodecForTr(textCodec) mainWindow = MainWindow() #mainWindow.show() app.exec_()
def read(self, line): self.vfile = self.node.open() padd = 0 if line > padd: padd = 1 self.vfile.seek(self.offsets[line]+padd) self.text.clear() codec = QTextCodec.codecForName(self.currentCodec) decoder = codec.makeDecoder() self.text.textCursor().insertText(decoder.toUnicode(self.vfile.read(1024*10))) self.text.moveCursor(QTextCursor.Start) self.vfile.close()
def __init__(self, bt, parent=None): QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8')) # qt中文字体 mpl.rcParams['font.sans-serif'] = ['SimHei'] # matplotlib中文指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 super(ExhibitionSubWindow, self).__init__(parent) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.ui = Ui_back_test_dialog() self.ui.setupUi(self) self.ui.equity_plot_layout.addWidget(self.toolbar) self.ui.equity_plot_layout.addWidget(self.canvas) self.order_model = None self.equity_axis = self.figure.add_subplot(111) self._backtest = bt self._backtest.set_exhibitor(self)
def read(self, line): self.vfile = self.node.open() padd = 0 if line > padd: padd = 1 self.vfile.seek(self.offsets[line] + padd) self.text.clear() codec = QTextCodec.codecForName(self.currentCodec) decoder = codec.makeDecoder() self.text.textCursor().insertText( decoder.toUnicode(self.vfile.read(1024 * 10))) self.text.moveCursor(QTextCursor.Start) self.vfile.close()
def __init__(self, parent = None): """ Constructor """ QTextCodec.setCodecForCStrings(QTextCodec.codecForName('gbk')) QMainWindow.__init__(self, parent) self.setupUi(self) self.caseDir = '' self.selectedCaseList = [] self.caselist = [] self.paramlist = [] self.bcasePause = False self.idoneCaseIndex = -1 self.idoneCaseIndex = 0 self.reportFileName = '' self.treeWidget_caseTree.itemChanged.connect(self.treehandleChanged) #设置table的列宽 self.tableWidget.setColumnWidth(0,180) self.tableWidget.setColumnWidth(1,70) self.tableWidget_caseList.setColumnWidth(0,150) self.getCommunicationConfig() self.casethread = workThread.autotest() self.casethread.sinOut1.connect(self.currentRunIndex) self.casethread.sinOut2.connect(self.process) self.casethread.sinOut3.connect(self.stopIndex) self.casethread.sinOut4.connect(self.endResult) self.casethread.sinOut5.connect(self.getReportFile) self.pushButton_start.setEnabled(False) self.pushButton_pause.setEnabled(False) try: self.caseDir = config.getTemp('caseDir') if self.caseDir != '': self.updateTree(self.caseDir) except Exception,e: print e
def __init__(self, shared): super(Backend, self).__init__() self.shared = shared self.sendto = lambda x: shared.udpsocket.sendto( x.encode('utf-8'), ('127.0.0.1', 50000) ) self._app = QApplication([]) translator = QTranslator(self._app) self._app.setQuitOnLastWindowClosed(False) translator.load( QLocale.system(), 'lang', '.', shared.path + sep + 'langs') self._app.installTranslator(translator) self.loadicons() QTextCodec.setCodecForTr(QTextCodec.codecForName("UTF-8")) self._tray = TrayIcon(self) self._tray.setIcon(_icons['wait']) self.signals = { 'add': self.sAdd, 'empty': lambda x: self._tray.emit(SIGNAL('empty()')), 'start': self.sStart, 'error': self.sDone, 'done': self.sDone, }
def main(args): App = QApplication(args) splash = QSplashScreen(QPixmap("./view/winView/imgs/splash.png")) splash.show() # 启动动画 App.processEvents() QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) initProperty() # 初始化 app.Music.play() # 开机音乐 app.MainWin.show() # 主窗口显示 splash.finish(app.MainWin) createTray() # 创建托盘 # 调试状态不连线上接服务器 if app.Debug: host = '114.215.209.164' # host = 'localhost' thread = Worker(None, host, 1234, app.AppUser, app.MainWin) # 子进程 thread.start() server = Server(None) # 子进程 server.start() # else: # # 打开工具箱 # app._tool_.show() App.exec_()
def loadFields(self, vectorFile): self.attributeComboBox.clear() if not vectorFile: return try: (fields, names) = Utils.getVectorFields(vectorFile) except Utils.UnsupportedOGRFormat as e: QErrorMessage(self).showMessage(e.args[0]) self.inSelector.setLayer(None) return ncodec = QTextCodec.codecForName(self.lastEncoding) for name in names: self.attributeComboBox.addItem(ncodec.toUnicode(name))
def loadFields(self, vectorFile=''): self.zfieldCombo.clear() if not vectorFile: return try: (fields, names) = Utils.getVectorFields(vectorFile) except Utils.UnsupportedOGRFormat as e: QErrorMessage(self).showMessage(e.args[0]) self.inSelector.setLayer(None) return ncodec = QTextCodec.codecForName(self.lastEncoding) for name in names: self.zfieldCombo.addItem(ncodec.toUnicode(name))
def __init__(self, page, parent=None): super(HelpForm, self).__init__(parent) QTextCodec.setCodecForTr(QTextCodec.codecForName("system")) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("system")) QTextCodec.setCodecForLocale(QTextCodec.codecForName("system")) self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_GroupLeader) backAction = QAction(QIcon(":/back.png"), "&Back", self) backAction.setShortcut(QKeySequence.Back) homeAction = QAction(QIcon(":/home.png"), "&Home", self) homeAction.setShortcut("Home") self.pageLabel = QLabel() toolBar = QToolBar() toolBar.addAction(backAction) toolBar.addAction(homeAction) toolBar.addWidget(self.pageLabel) self.textBrowser = QTextBrowser() # self.textBrowser. layout = QVBoxLayout() layout.addWidget(toolBar) layout.addWidget(self.textBrowser, 1) self.setLayout(layout) self.connect(backAction, SIGNAL("triggered()"), self.textBrowser, SLOT("backward()")) self.connect(homeAction, SIGNAL("triggered()"), self.textBrowser, SLOT("home()")) self.connect(self.textBrowser, SIGNAL("sourceChanged(QUrl)"), self.updatePageTitle) self.textBrowser.setSearchPaths([":/help"]) self.textBrowser.setSource(QUrl(page)) self.resize(400, 600) self.setWindowTitle("%s Help" % QApplication.applicationName())
def main(): qapp = QApplication(sys.argv) tc = QTextCodec.codecForName('utf-8') QTextCodec.setCodecForCStrings(tc) QTextCodec.setCodecForLocale(tc) QTextCodec.setCodecForTr(tc) app.g_pwd = os.getcwd() print app.g_pwd #遍历目录 tmpdirs = os.listdir(app.g_pwd + os.sep + 'templates') for tmpdir in tmpdirs: currentdir = app.g_pwd + os.sep + 'templates' + os.sep + tmpdir if os.path.isdir(currentdir) and os.path.exists(currentdir + os.sep + 'config.json'): app.g_templates.append(tmpdir) m = mainwindow.mainwindow() m.show() qapp.exec_()
def __init__(self): super(Ui_MainWindow, self).__init__() self.setupUi(self) self.retranslateUi(self) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("utf-8"))
def __init__(self, f=None, geojson=None, datatype='polygon'): """ Can initialize with either a file, or a geojson. Note datatype is ignored unless geojson is used. """ self.isValid = False if f and not geojson: l = QgsVectorLayer(f, "calculation boundary", "ogr") log("Geom type: {}, {}".format(l.geometryType(), QGis.Polygon)) if not l.isValid(): return if l.geometryType() == QGis.Polygon: datatype = "polygon" elif l.geometryType() == QGis.Point: datatype = "point" else: QtGui.QMessageBox.critical(None, tr("Error"), tr("Failed to process area of interest - unknown geometry type:{}".format(l.geometryType()))) log("Failed to process area of interest - unknown geometry type.") return elif not f and geojson: l = QgsVectorLayer("{}?crs=epsg:4326".format(datatype), "calculation boundary", "memory") fields = QgsJSONUtils.stringToFields(json.dumps(geojson), QTextCodec.codecForName('UTF8')) features = QgsJSONUtils.stringToFeatureList(json.dumps(geojson), fields, QTextCodec.codecForName('UTF8')) ret = l.dataProvider().addFeatures(features) l.commitChanges() if not ret: QtGui.QMessageBox.critical(None, tr("Error"), tr("Failed to add geojson to temporary layer.")) log("Failed to add geojson to temporary layer.") return l.commitChanges() else: raise ValueError("Must specify file or geojson") crs_source = l.crs() crs_dest = QgsCoordinateReferenceSystem(4326) t = QgsCoordinateTransform(crs_source, crs_dest) # Transform layer to WGS84 l_wgs84 = QgsVectorLayer("{}?crs=epsg:4326".format(datatype), "calculation boundary (wgs84)", "memory") #CRS transformation feats = [] for f in l.getFeatures(): g = f.geometry() g.transform(t) f.setGeometry(g) feats.append(f) l_wgs84.dataProvider().addFeatures(feats) l_wgs84.commitChanges() if not l_wgs84.isValid(): self.layer = None log("Error transforming AOI coordinates to WGS84") return else: self.layer = l_wgs84 # Transform bounding box to WGS84 self.bounding_box_geom = QgsGeometry.fromRect(l_wgs84.extent()) # Save a geometry of the bounding box self.bounding_box_geom.transform(t) # Also save a geojson of the bounding box (needed for shipping to GEE) self.bounding_box_geojson = json.loads(self.bounding_box_geom.exportToGeoJSON()) # Check the coordinates of the bounding box are now in WGS84 (in case # no transformation was available for the chosen coordinate systems) bbox = self.bounding_box_geom.boundingBox() log("Bounding box: {}, {}, {}, {}".format(bbox.xMaximum(), bbox.xMinimum(), bbox.yMinimum(), bbox.yMinimum())) if (bbox.xMinimum() < -180) or \ (bbox.xMaximum() > 180) or \ (bbox.yMinimum() < -90) or \ (bbox.yMinimum() > 90): QtGui.QMessageBox.critical(None, tr("Error"), tr("Coordinates of area of interest could not be transformed to WGS84. Check that the projection system is defined."), None) log("Error transforming AOI coordinates to WGS84") else: self.isValid = True
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking global cursor_flash_time cursor_flash_time = app.cursorFlashTime() app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = QSettings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', language) + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists( file_manager.create_path(resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path(resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default") if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) tempFiles.append((fileData[0], int(fileData[1]))) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) tempFiles.append((fileData[0], int(fileData[1]))) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list( map(lambda f: (f[0], f[1] - 1), zip(filenames, linenos))) file_without_nro = list(map(lambda f: (f, 0), filenames[len(linenos):])) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() sys.exit(app.exec_())
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking #if not settings.IS_WINDOWS: #app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) #Set Stylesheet style_applied = False print(settings.NINJA_SKIN) if settings.NINJA_SKIN not in ('Default'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value('lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], (f[1] - 1, 0), 0) for f in zip(filenames, linenos)]) file_without_nro = list([(f, (0, 0), 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if not settings.IS_WINDOWS: app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA_THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value( 'lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()
__version__ = "0.0.0" import sip sip.setapi( "QString", 2 ) import sys, os, os.path, gc from PyQt4.QtCore import QTimer, QDir, QTextCodec try: # Dirty hack to have default encoding set. # Otherwise national letters in input fields will lead to # exceptions/incorrect behavior reload( sys ) sys.setdefaultencoding( "utf-8" ) QTextCodec.setCodecForCStrings( QTextCodec.codecForName( "utf-8" ) ) except AttributeError: pass # Workaround if link is used sys.argv[0] = os.path.realpath( sys.argv[0] ) # Make it possible to import from the subdirectories srcDir = os.path.dirname( os.path.abspath( sys.argv[0] ) ) if not srcDir in sys.path: sys.path.insert( 0, srcDir ) ropeDir = srcDir + os.path.sep + "thirdparty" + os.path.sep + "rope" if not ropeDir in sys.path: sys.path.insert( 0, ropeDir ) filemagicDir = srcDir + os.path.sep + "thirdparty" + os.path.sep + "filemagic"
def __init__(self): QtProxyCodec.__init__(self, QTextCodec.codecForName('utf-8'), 'utf-8')
def __init__(self, little_endian=True): enc_name = 'utf-32le' if little_endian else 'utf-32be' QtProxyCodec.__init__(self, QTextCodec.codecForName(enc_name), enc_name) self.littleEndian = little_endian
'Windows-1258', 'IBM-850', 'IBM-866', 'IBM-874', 'AppleRoman', 'KOI8-R', 'KOI8-U', 'roman8' ) encodings = { 'UTF-8': Utf8Codec(), 'UTF-16LE': Utf16Codec(little_endian=True), 'UTF-16BE': Utf16Codec(little_endian=False), 'UTF-32LE': Utf32Codec(little_endian=True), 'UTF-32BE': Utf32Codec(little_endian=False) } for encoding in singlebyte_encodings: qcodec = QTextCodec.codecForName(encoding) if qcodec is not None: encodings[encoding] = SingleByteEncodingCodec(qcodec, encoding) def getCodec(name): name = name.lower() for key in encodings.keys(): if key.lower() == name: return encodings[key] return None
def getEncodings(): """Returns a list of available encodings static.""" return [unicode(QTextCodec.codecForMib(mib).name()) for mib in QTextCodec.availableMibs()]
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see SMlib/__init__.py for details) """External System Shell widget: execute terminal in a separate process""" import os from PyQt4.QtGui import QMessageBox from PyQt4.QtCore import QProcess, SIGNAL, QTextCodec locale_codec = QTextCodec.codecForLocale() # Local imports from SMlib.utils import encoding from SMlib.utils.programs import shell_split from SMlib.configs.baseconfig import _ from SMlib.utils.qthelpers import get_icon from SMlib.widgets.externalshell.baseshell import (ExternalShellBase, add_pathlist_to_PYTHONPATH) from SMlib.widgets.shell import TerminalWidget class ExternalSystemShell(ExternalShellBase): """External Shell widget: execute Python script in a separate process""" SHELL_CLASS = TerminalWidget def __init__(self, parent=None, wdir=None, path=[], light_background=True, menu_actions=None, show_buttons_inside=True, show_elapsed_time=True): ExternalShellBase.__init__(self, parent=parent, fname=None, wdir=wdir,
import sys import locale from PyQt4.QtGui import QApplication from PyQt4.QtCore import QTextCodec from mainwnd import CraneTestDocWnd if __name__ == "__main__": app = QApplication(sys.argv) mycode = locale.getpreferredencoding() code = QTextCodec.codecForName(mycode) QTextCodec.setCodecForLocale(code) QTextCodec.setCodecForTr(code) QTextCodec.setCodecForCStrings(code) wnd = CraneTestDocWnd() wnd.show() # wi = MyWidget() # wi.show() app.exec_()
# Finish codes in addition to the normal exit code KILLED = -1000000 DISCONNECTED = -2000000 NEXT_ID = 0 def getNextID(): " Provides the next available ID " global NEXT_ID current = int( NEXT_ID ) NEXT_ID += 1 return current CODEC = QTextCodec.codecForName( "utf-8" ) class RemoteProcessWrapper( QObject ): " Wrapper to control the remote process " PROTOCOL_CONTROL = 0 PROTOCOL_STDOUT = 1 PROTOCOL_STDERR = 2 def __init__( self, path, serverPort ): QObject.__init__( self ) self.__procID = getNextID() self.__path = path self.__serverPort = serverPort self.__clientSocket = None
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see SMlib/__init__.py for details) """External System Shell widget: execute terminal in a separate process""" import os from PyQt4.QtGui import QMessageBox from PyQt4.QtCore import QProcess, SIGNAL, QTextCodec locale_codec = QTextCodec.codecForLocale() # Local imports from SMlib.utils import encoding from SMlib.utils.programs import shell_split from SMlib.configs.baseconfig import _ from SMlib.utils.qthelpers import get_icon from SMlib.widgets.externalshell.baseshell import (ExternalShellBase, add_pathlist_to_PYTHONPATH) from SMlib.widgets.shell import TerminalWidget class ExternalSystemShell(ExternalShellBase): """External Shell widget: execute Python script in a separate process""" SHELL_CLASS = TerminalWidget def __init__(self, parent=None, wdir=None, path=[],
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking global cursor_flash_time cursor_flash_time = app.cursorFlashTime() app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = QSettings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', language) + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists(file_manager.create_path( resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path( resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default") if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) tempFiles.append((fileData[0], int(fileData[1]))) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) tempFiles.append((fileData[0], int(fileData[1]))) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list(map(lambda f: (f[0], f[1] - 1), zip(filenames, linenos))) file_without_nro = list(map(lambda f: (f, 0), filenames[len(linenos):])) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() sys.exit(app.exec_())
def __init__(self, config): super(FreeseerApp, self).__init__() self.config = config self.icon = QIcon() self.icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(self.icon) self.aboutDialog = AboutDialog() self.aboutDialog.setModal(True) self.logDialog = LogDialog() # # Translator # self.app = QApplication.instance() self.current_language = None self.uiTranslator = QTranslator() self.uiTranslator.load(":/languages/tr_en_US.qm") self.app.installTranslator(self.uiTranslator) self.langActionGroup = QActionGroup(self) self.langActionGroup.setExclusive(True) QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8')) self.connect(self.langActionGroup, SIGNAL('triggered(QAction *)'), self.translate) # --- Translator # # Setup Menubar # self.menubar = self.menuBar() self.menubar.setGeometry(self.qrect_with_dpi(0, 0, 500, 50)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) self.menuLanguage = QMenu(self.menubar) self.menuLanguage.setObjectName(_fromUtf8("menuLanguage")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) exitIcon = QIcon.fromTheme("application-exit") self.actionExit = QAction(self) self.actionExit.setShortcut("Ctrl+Q") self.actionExit.setObjectName(_fromUtf8("actionExit")) self.actionExit.setIcon(exitIcon) helpIcon = QIcon.fromTheme("help-contents") self.actionOnlineHelp = QAction(self) self.actionOnlineHelp.setObjectName(_fromUtf8("actionOnlineHelp")) self.actionOnlineHelp.setIcon(helpIcon) self.actionAbout = QAction(self) self.actionAbout.setObjectName(_fromUtf8("actionAbout")) self.actionAbout.setIcon(self.icon) self.actionLog = QAction(self) self.actionLog.setObjectName(_fromUtf8("actionLog")) self.actionLog.setShortcut("Ctrl+L") # Actions self.menuFile.addAction(self.actionExit) self.menuHelp.addAction(self.actionAbout) self.menuHelp.addAction(self.actionLog) self.menuHelp.addAction(self.actionOnlineHelp) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuLanguage.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.setupLanguageMenu() # --- End Menubar self.connect(self.actionExit, SIGNAL('triggered()'), self.close) self.connect(self.actionAbout, SIGNAL('triggered()'), self.aboutDialog.show) self.connect(self.actionLog, SIGNAL('triggered()'), self.logDialog.show) self.connect(self.actionOnlineHelp, SIGNAL('triggered()'), self.openOnlineHelp) self.retranslateFreeseerApp() self.aboutDialog.aboutWidget.retranslate("en_US")
def start(listener, filenames=None, projects_path=None, extra_plugins=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking app.setCursorFlashTime(0) #Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = QSettings() language = QLocale.system().language() lang = unicode(qsettings.value( 'preferences/interface/language', language).toString()) + '.qm' lang_path = file_manager.create_path(resources.LANGS, unicode(lang)) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists(file_manager.create_path( resources.LANGS_DOWNLOAD, unicode(lang))): settings.LANGUAGE = file_manager.create_path( resources.LANGS_DOWNLOAD, unicode(lang)) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Loading Themes splash.showMessage("Loading Themes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = unicode(qsettings.value('preferences/editor/scheme', "default").toString()) if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE() #Showing GUI ide.show() #Connect listener signals ide.connect(listener, SIGNAL("fileOpenRequested(QString)"), ide.open_file) ide.connect(listener, SIGNAL("projectOpenRequested(QString)"), ide.open_project) #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab mainFiles = qsettings.value('openFiles/mainTab', []).toList() tempFiles = [] for file_ in mainFiles: fileData = file_.toList() tempFiles.append((unicode(fileData[0].toString()), fileData[1].toInt()[0])) mainFiles = tempFiles #Files in Secondary Tab secondaryFiles = qsettings.value('openFiles/secondaryTab', []).toList() tempFiles = [] for file_ in secondaryFiles: fileData = file_.toList() tempFiles.append((unicode(fileData[0].toString()), fileData[1].toInt()[0])) secondaryFiles = tempFiles #Projects projects = qsettings.value('openFiles/projects', []).toList() projects = [unicode(project.toString()) for project in projects] #Include files received from console args if filenames: mainFiles += [(f, 0) for f in filenames] #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() sys.exit(app.exec_())
def __init__(self, config): super(FreeseerApp, self).__init__() self.config = config self.icon = QIcon() self.icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(self.icon) self.aboutDialog = AboutDialog() self.aboutDialog.setModal(True) self.logDialog = LogDialog() # # Translator # self.app = QApplication.instance() self.current_language = None self.uiTranslator = QTranslator() self.uiTranslator.load(":/languages/tr_en_US.qm") self.app.installTranslator(self.uiTranslator) self.langActionGroup = QActionGroup(self) self.langActionGroup.setExclusive(True) QTextCodec.setCodecForTr(QTextCodec.codecForName('utf-8')) self.connect(self.langActionGroup, SIGNAL('triggered(QAction *)'), self.translate) # --- Translator # # Setup Menubar # self.menubar = self.menuBar() self.menubar.setGeometry(QRect(0, 0, 500, 50)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) self.menuLanguage = QMenu(self.menubar) self.menuLanguage.setObjectName(_fromUtf8("menuLanguage")) self.menuHelp = QMenu(self.menubar) self.menuHelp.setObjectName(_fromUtf8("menuHelp")) exitIcon = QIcon.fromTheme("application-exit") self.actionExit = QAction(self) self.actionExit.setShortcut("Ctrl+Q") self.actionExit.setObjectName(_fromUtf8("actionExit")) self.actionExit.setIcon(exitIcon) helpIcon = QIcon.fromTheme("help-contents") self.actionOnlineHelp = QAction(self) self.actionOnlineHelp.setObjectName(_fromUtf8("actionOnlineHelp")) self.actionOnlineHelp.setIcon(helpIcon) self.actionAbout = QAction(self) self.actionAbout.setObjectName(_fromUtf8("actionAbout")) self.actionAbout.setIcon(self.icon) self.actionLog = QAction(self) self.actionLog.setObjectName(_fromUtf8("actionLog")) self.actionLog.setShortcut("Ctrl+L") # Actions self.menuFile.addAction(self.actionExit) self.menuHelp.addAction(self.actionAbout) self.menuHelp.addAction(self.actionLog) self.menuHelp.addAction(self.actionOnlineHelp) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuLanguage.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.setupLanguageMenu() # --- End Menubar self.connect(self.actionExit, SIGNAL('triggered()'), self.close) self.connect(self.actionAbout, SIGNAL('triggered()'), self.aboutDialog.show) self.connect(self.actionLog, SIGNAL('triggered()'), self.logDialog.show) self.connect(self.actionOnlineHelp, SIGNAL('triggered()'), self.openOnlineHelp) self.retranslateFreeseerApp() self.aboutDialog.aboutWidget.retranslate("en_US")
#!/usr/bin/env python #coding=utf-8 ''' FileName : main.py ''' import sys from PyQt4.QtCore import QTextCodec from PyQt4.QtGui import QApplication from connection import createConnection from mainwindow import MainWindow if __name__ == "__main__": app = QApplication(sys.argv) # 这行代码要写在创建连接之前, 不然,数据库中文乱码 QTextCodec.setCodecForTr(QTextCodec.codecForName("UTF-8")) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")) if not createConnection(): raise Exception("createConnection faild") win = MainWindow() win.show() app.exec_()
# Form implementation generated from reading ui file 'dialog2.ui' # # Created: Wed Sep 23 10:49:32 2015 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from PyQt4.QtGui import QMainWindow, QIcon, QMessageBox import os from business import clickExportFile, cleanup from PyQt4.QtCore import QTextCodec from dialog3 import Ui_dialog3 QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8")) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("GBK")) try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding)
# coding:UTF-8 from OpenOffice import OpenOffice from PyQt4.QtGui import QTextListFormat from PyQt4.QtGui import QTextFrameFormat from PyQt4.QtGui import QColor from PyQt4.QtCore import QTextCodec QTextCodec.setCodecForTr(QTextCodec.codecForName("UTF-8")) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8")); QTextCodec.setCodecForLocale(QTextCodec.codecForName("UTF-8")); office = OpenOffice('走你.odt') # Insert some text office.setListFormat(QTextListFormat.ListUpperAlpha) office.insertImage("./123.png", 50, 200, QTextFrameFormat.FloatRight) office.insertList() office.insertText("中文\n") office.insertText("two\n") office.insertText("three\n") office.insertText("\n") office.insertText("\n") office.insertText("\n")
from src.gui.library import insert_library from src.tools.config import Config from PyQt4.Qt import QDialog, pyqtSignal, QProgressDialog from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt, QThread, QTextCodec, QSettings, QVariant, QSize, QPoint from src.gui.dialogs.ui_download import Ui_Dialog from src.web.feeds.recipes.model import RecipeModel from src.tools.path import Path from src.login import Login from src.main import EEBook from src.constants import EPUBSTOR_DIR, LIBRARY_DIR, ISOTIMEFORMAT QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8")) class DownloadDialog(QDialog, Ui_Dialog): download = pyqtSignal(object) def __init__(self, recipe_model, book_view, parent=None): QDialog.__init__(self, parent) self.now_url = '' self.book_view = book_view self.setAttribute(Qt.WA_DeleteOnClose) # 每次关闭对话框删除对话框所占的内存 self.setupUi(self) self.recipe_model = recipe_model self.recipe_model.showing_count = 3 # TODO, 改掉这里的硬编码 self.count_label.setText(
#! /usr/bin/env python #coding: u8 import sys from PyQt4.QtGui import QMainWindow, QApplication from PyQt4.QtCore import QTextCodec, Qt, QFile, QLatin1String, SIGNAL, pyqtSlot QTextCodec.setCodecForTr(QTextCodec.codecForName('u8')) import settings if settings.DEBUG: # 调试的时候每次都转换一下qrc和ui文件 import gen gen.run() # 开启js调试[相当于chrome的审查元素] from PyQt4 import QtWebKit s = QtWebKit.QWebSettings s.globalSettings().setAttribute(s.DeveloperExtrasEnabled, True) import window class MainWindow(QMainWindow, window.Ui_main_window): def __init__(self, app, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.app = app
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName("NINJA-IDE") QCoreApplication.setOrganizationDomain("NINJA-IDE") QCoreApplication.setApplicationName("NINJA-IDE") app.setWindowIcon(QIcon(resources.IMAGES["icon"])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES["splash"]) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if not settings.IS_WINDOWS: app.setCursorFlashTime(0) # Set the codec for strings (QString) QTextCodec.setCodecForCStrings(QTextCodec.codecForName("utf-8")) # Translator qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) language = QLocale.system().name() lang = qsettings.value("preferences/interface/language", defaultValue=language, type="QString") + ".qm" lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) # Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() # Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() # Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ("Default", "Classic Theme"): file_name = "%s.qss" % settings.NINJA_SKIN qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == "Default": with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA_THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) # Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value("preferences/editor/scheme", "default", type="QString") if scheme != "default": scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + ".color") if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) # Loading Shortcuts resources.load_shortcuts() # Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) # Showing GUI ninjaide.show() # Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) # First check if we need to load last session files if qsettings.value("preferences/general/loadFiles", True, type=bool): # Files in Main Tab main_files = qsettings.value("openFiles/mainTab", []) tempFiles = [] if main_files: for file_ in main_files: fileData = list(file_) if fileData: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) main_files = tempFiles # Files in Secondary Tab sec_files = qsettings.value("openFiles/secondaryTab", []) tempFiles = [] if sec_files: for file_ in sec_files: fileData = list(file_) if fileData: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) sec_files = tempFiles # Recent Files recent_files = qsettings.value("openFiles/recentFiles", []) # Current File current_file = qsettings.value("openFiles/currentFile", "", type="QString") # Projects projects = qsettings.value("openFiles/projects", []) else: main_files = [] sec_files = [] recent_files = [] current_file = "" projects = [] # Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos) :]]) main_files += file_with_nro + file_without_nro # Include projects received from console args if projects_path: projects += projects_path # FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT # ninjaide.load_session_files_projects(main_files, sec_files, # projects, current_file, recent_files) # Load external plugins # if extra_plugins: # ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()