Esempio n. 1
0
    def aboutToShowSaveAsMenu(self):
        currentText = self.textEdit.toPlainText()

        for action in self.saveAsActs:
            codecName = action.data()
            codec = QTextCodec.codecForName(codecName)
            action.setVisible(codec and codec.canEncode(currentText))
Esempio n. 2
0
 def __init__(self):
     # Create a byte array that stays in scope as long as we do
     self.buffer = QByteArray()
     # Initialize the "real" QTextStream with a ByteArray buffer.
     super().__init__(self.buffer, QIODevice.ReadWrite)
     # The default codec is codecForLocale, which might vary with
     # the platform, so set a codec here for consistency. UTF-16
     # should entail minimal or no conversion on input or output.
     self.setCodec( QTextCodec.codecForName('UTF-16') )
Esempio n. 3
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
		                for alias in QTextCodec.availableCodecs())
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in sorted(codecsSet)],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(None, encoding)
Esempio n. 4
0
    def read_file(self, path):
        """Read in a file
        """
        file = QFile(path)
        fileinfo = QFileInfo(file)

        file.open(QIODevice.ReadOnly)
        data = file.readAll()
        codec = QTextCodec.codecForName("UTF-8")

        self.contents = codec.toUnicode(data).rstrip("\n")

        self.filename = fileinfo.fileName()
Esempio n. 5
0
def loadTranslators(qtTransDir, app, translationFiles=()):
    """
    Module function to load all required translations.
    
    @param qtTransDir directory of the Qt translations files (string)
    @param app reference to the application object (QApplication)
    @param translationFiles tuple of additional translations to
        be loaded (tuple of strings)
    @return the requested locale (string)
    """
    import Preferences
    
    global loaded_translators
    
    if qVersion() < "5.0.0":
        # set the default encoding for tr()
        QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))
    
    translations = ("qt", "eric6") + translationFiles
    loc = Preferences.getUILanguage()
    if loc is None:
        return

    if loc == "System":
        loc = QLocale.system().name()
    if loc != "C":
        dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
        if qtTransDir is not None:
            dirs.append(qtTransDir)

        loca = loc
        for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
            translator, ok = loadTranslatorForLocale(dirs, tf)
            loaded_translators[tf] = translator
            if ok:
                app.installTranslator(translator)
            else:
                if tf.startswith("eric6"):
                    loca = None
        loc = loca
    else:
        loc = None
    return loc
 def __init__(self, debugServer, passive):
     """
     Constructor
     
     @param debugServer reference to the debug server (DebugServer)
     @param passive flag indicating passive connection mode (boolean)
     """
     super(DebuggerInterfacePython, self).__init__()
     
     self.__isNetworked = True
     self.__autoContinue = False
     
     self.debugServer = debugServer
     self.passive = passive
     self.process = None
     
     self.qsock = None
     self.queue = []
     
     # set default values for capabilities of clients
     self.clientCapabilities = ClientDefaultCapabilities
     
     # set translation function
     self.translate = self.__identityTranslation
     
     self.codec = QTextCodec.codecForName(
         Preferences.getSystem("StringEncoding"))
     
     self.__unicodeRe = re.compile(r"""\bu(["'])""")
     
     if passive:
         # set translation function
         if Preferences.getDebugger("PathTranslation"):
             self.translateRemote = \
                 Preferences.getDebugger("PathTranslationRemote")
             self.translateLocal = \
                 Preferences.getDebugger("PathTranslationLocal")
             self.translate = self.__remoteTranslation
         else:
             self.translate = self.__identityTranslation
     
     # attribute to remember the name of the executed script
     self.__scriptName = ""
Esempio n. 7
0
 def __init__(self, debugServer, passive):
     """
     Constructor
     
     @param debugServer reference to the debug server (DebugServer)
     @param passive flag indicating passive connection mode (boolean)
     """
     super(DebuggerInterfaceRuby, self).__init__()
     
     self.__isNetworked = True
     self.__autoContinue = not passive
     
     self.debugServer = debugServer
     self.passive = passive
     self.process = None
     
     self.qsock = None
     self.queue = []
     
     # set default values for capabilities of clients
     self.clientCapabilities = ClientDefaultCapabilities
     
     # set translation function
     self.translate = self.__identityTranslation
     
     self.codec = QTextCodec.codecForName(
         str(Preferences.getSystem("StringEncoding")))
     
     if passive:
         # set translation function
         if Preferences.getDebugger("PathTranslation"):
             self.translateRemote = \
                 Preferences.getDebugger("PathTranslationRemote")
             self.translateLocal = \
                 Preferences.getDebugger("PathTranslationLocal")
             self.translate = self.__remoteTranslation
         else:
             self.translate = self.__identityTranslation
Esempio n. 8
0
    def __init__(self, debugServer, passive):
        """
        Constructor
        
        @param debugServer reference to the debug server (DebugServer)
        @param passive flag indicating passive connection mode (boolean)
        """
        super(DebuggerInterfaceRuby, self).__init__()

        self.__isNetworked = True
        self.__autoContinue = not passive

        self.debugServer = debugServer
        self.passive = passive
        self.process = None

        self.qsock = None
        self.queue = []

        # set default values for capabilities of clients
        self.clientCapabilities = ClientDefaultCapabilities

        # set translation function
        self.translate = self.__identityTranslation

        self.codec = QTextCodec.codecForName(
            str(Preferences.getSystem("StringEncoding")))

        if passive:
            # set translation function
            if Preferences.getDebugger("PathTranslation"):
                self.translateRemote = \
                    Preferences.getDebugger("PathTranslationRemote")
                self.translateLocal = \
                    Preferences.getDebugger("PathTranslationLocal")
                self.translate = self.__remoteTranslation
            else:
                self.translate = self.__identityTranslation
Esempio n. 9
0
    def __init__(self, parent, readonly=False):
        super(DeenEncoderWidget, self).__init__(parent)
        self.ui = Ui_DeenEncoderWidget()
        self.parent = parent
        self.readonly = readonly
        self.process = False
        self.plugin = None
        self.search_matches = None
        self._content = bytearray()
        self.codec = QTextCodec.codecForName('UTF-8')
        self.hex_view = False
        self.formatted_view = False
        # TODO: check if printable is enforced
        self.printable = True

        # Assign custom widgets for text_field and hex_field.
        self.text_field = TextViewWidget(self, readonly=self.readonly)
        self.text_field.textChanged.connect(self.field_content_changed)
        self.hex_field = HexViewWidget(read_only=self.readonly, parent=self)
        self.hex_field.setHidden(True)
        self.formatted_field = FormattedViewWidget(self,
                                                   readonly=self.readonly)
        self.formatted_field.setHidden(True)
        self.formatted_field.textChanged.connect(self.field_content_changed)
        # Add connection for selection field
        self.text_field.selectionChanged.connect(self.update_selection_field)
        self.formatted_field.selectionChanged.connect(
            self.update_selection_field)
        self.hex_field.bytesChanged.connect(self.field_content_changed)
        self.hex_field.itemSelectionChanged.connect(
            self.update_selection_field)

        # setupUi() access the field self._content, thus it must be initialized first:
        self.ui.setupUi(self)

        self.ui.selection_length_label.setText('Selection: 0')
        self.ui.content_area_layout.addWidget(self.text_field)
        self.ui.content_area_layout.addWidget(self.hex_field)
        self.ui.content_area_layout.addWidget(self.formatted_field)
        # Configure widget elements
        self.ui.toggle_text_view.setChecked(True)
        self.ui.toggle_text_view.clicked.connect(self.view_text)
        self.toggle_button_border(self.ui.toggle_text_view)
        self.ui.toggle_hex_view.setChecked(False)
        self.ui.toggle_hex_view.clicked.connect(self.view_hex)
        self.ui.toggle_formatted_view.setChecked(False)
        self.ui.toggle_formatted_view.clicked.connect(self.view_formatted)
        # Add icons to buttons
        icon_path = MEDIA_PATH
        if self.palette().color(self.backgroundRole()).value() < 128:
            icon_path += 'dark/'
        if all([
                os.path.exists(icon_path + 'view-text.svg'),
                os.path.exists(icon_path + 'view-hex.svg'),
                os.path.exists(icon_path + 'view-formatted.svg')
        ]):
            self.ui.toggle_text_view.setIcon(QIcon(icon_path +
                                                   'view-text.svg'))
            self.ui.toggle_text_view.setText('')
            self.ui.toggle_hex_view.setIcon(QIcon(icon_path + 'view-hex.svg'))
            self.ui.toggle_hex_view.setText('')
            self.ui.toggle_formatted_view.setIcon(
                QIcon(icon_path + 'view-formatted.svg'))
            self.ui.toggle_formatted_view.setText('')
        # Update labels with proper values
        self.update_length_field()
        # Create references for tree view items
        self.plugin_tree_top_decode = self.ui.plugin_tree_view.topLevelItem(0)
        self.plugin_tree_top_encode = self.ui.plugin_tree_view.topLevelItem(1)
        self.plugin_tree_top_uncompress = self.ui.plugin_tree_view.topLevelItem(
            2)
        self.plugin_tree_top_compress = self.ui.plugin_tree_view.topLevelItem(
            3)
        self.plugin_tree_top_disassemble = self.ui.plugin_tree_view.topLevelItem(
            4)
        self.plugin_tree_top_assemble = self.ui.plugin_tree_view.topLevelItem(
            5)
        self.plugin_tree_top_hash = self.ui.plugin_tree_view.topLevelItem(6)
        self.plugin_tree_top_misc = self.ui.plugin_tree_view.topLevelItem(7)
        self.plugin_tree_top_format = self.ui.plugin_tree_view.topLevelItem(8)
        # Add tree items for the plugin tree view
        for encoding in [
                p[1] for p in self.parent.plugins.codecs
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_encode.addChild(
                QTreeWidgetItem([encoding.display_name]))
        for encoding in [
                p[1] for p in self.parent.plugins.codecs
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_decode.addChild(
                QTreeWidgetItem([encoding.display_name]))
        for compression in [
                p[1] for p in self.parent.plugins.compressions
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_compress.addChild(
                QTreeWidgetItem([compression.display_name]))
        for compression in [
                p[1] for p in self.parent.plugins.compressions
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_uncompress.addChild(
                QTreeWidgetItem([compression.display_name]))
        for assembly in [
                p[1] for p in self.parent.plugins.assemblies
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_assemble.addChild(
                QTreeWidgetItem([assembly.display_name]))
        for assembly in [
                p[1] for p in self.parent.plugins.assemblies
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_disassemble.addChild(
                QTreeWidgetItem([assembly.display_name]))
        for hashalg in [
                p[1] for p in self.parent.plugins.hashs
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_hash.addChild(
                QTreeWidgetItem([hashalg.display_name]))
        for misc in [
                p[1] for p in self.parent.plugins.misc
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_misc.addChild(
                QTreeWidgetItem([misc.display_name]))
        for formatter in [
                p[1] for p in self.parent.plugins.formatters
                if (not getattr(p[1], 'cmd_only', None) or (
                    getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
        ]:
            self.plugin_tree_top_format.addChild(
                QTreeWidgetItem([formatter.display_name]))
        # Connect signal to tree view
        self.ui.plugin_tree_view.itemClicked.connect(self.action)
        self.ui.plugin_tree_view.currentItemChanged.connect(self.action)
        self.ui.plugin_tree_view.setMaximumWidth(
            self.ui.plugin_tree_view.columnWidth(0) * 2)
        # Hide top level items without any loaded plugins
        for i in range(self.ui.plugin_tree_view.topLevelItemCount()):
            tl_item = self.ui.plugin_tree_view.topLevelItem(i)
            if not tl_item:
                continue
            if tl_item.childCount() < 1:
                tl_item.setHidden(True)
        # Configure search widget
        self.ui.search_area.returnPressed.connect(self.search_highlight)
        self.ui.search_button.clicked.connect(self.search_highlight)
        self.ui.search_clear_button.clicked.connect(
            self.clear_search_highlight)
        self.ui.search_progress_bar.hide()
        self.error_message = QLabel()
        self.error_message.setStyleSheet('border: 2px solid red;')
        self.error_message.hide()
        self.ui.error_message_layout.addWidget(self.error_message)
        self.ui.error_message_layout_widget.hide()
        self.ui.search_group.hide()
        # After adding new widgets, we have to update the max scroll range.
        self.parent.ui.DeenMainWindow.verticalScrollBar().rangeChanged.connect(
            self.update_vertical_scroll_range)
        self.parent.ui.DeenMainWindow.horizontalScrollBar(
        ).rangeChanged.connect(self.update_horizontal_scroll_range)
Esempio n. 10
0
#!/usr/bin/env python3
#
import sys
import os
import configparser as parser
from PyQt5.QtCore import (QFile, QTextStream, Qt, QFileInfo, QTextCodec, QSize,
                          QPoint)
from PyQt5.QtGui import (QTextCursor, QFont, QKeySequence)
from PyQt5.QtWidgets import (QMainWindow, QApplication, QPlainTextEdit, QMenu,
                             QDesktopWidget, QMessageBox, QAction, QDialog,
                             QLabel, QPushButton, QDialogButtonBox,
                             QHBoxLayout, QVBoxLayout, QGridLayout, QLayout,
                             QLineEdit, QFontDialog)
from PyQt5.QtPrintSupport import QPrintDialog, QPrinter

QTextCodec.setCodecForLocale(QTextCodec.codecForName("UTF-8"))
CONFIG_FILE_PATH = "notepad.ini"


class Notepad(QMainWindow):
    def __init__(self):
        self.judgeConfigFile()
        self.clipboard = QApplication.clipboard()
        self.lastSearchText = ""
        self.lastReplaceSearchText = ""
        self.reset = False
        self.config = parser.ConfigParser()
        self.config.read(CONFIG_FILE_PATH)

        QMainWindow.__init__(self)
        self.initUI()
Esempio n. 11
0
    def handle_response(self, response, search_text: str):
        try:
            if response.status_code != 200:
                if not isinstance(response.exception, RequestsExceptionUserAbort):
                    info("Error in main response with status code: "
                         "{} from {}".format(response.status_code, response.url))
                return

            display_name_field = QgsField('display_name', QVariant.String)
            fields = QgsFields()
            fields.append(display_name_field)
            features = QgsJsonUtils.stringToFeatureList(response.content.decode('utf-8'), fields, QTextCodec.codecForName('UTF-8'))
            dbg_info('Found {} features'.format(len(features)))
            dbg_info('Data {}'.format(response.content.decode('utf-8')))

            for feature in features:
                dbg_info('Adding feature {}'.format(feature['display_name']))
                result = QgsLocatorResult()
                result.filter = self
                result.group = 'Objekte'
                result.displayString = feature['display_name']
                result.userData = FeatureResult(feature)
                self.resultFetched.emit(result)

                self.result_found = True

        except Exception as e:
            info(str(e), Qgis.Critical)
            exc_type, exc_obj, exc_traceback = sys.exc_info()
            filename = os.path.split(
                exc_traceback.tb_frame.f_code.co_filename)[1]
            info('{} {} {}'.format(exc_type, filename,
                                   exc_traceback.tb_lineno), Qgis.Critical)
            info(traceback.print_exception(
                exc_type, exc_obj, exc_traceback), Qgis.Critical)
Esempio n. 12
0
 def __init__(self, conf="qt.conf", parent=None):
     super(Settings, self).__init__(conf, QSettings.IniFormat, parent)
     self.setIniCodec(QTextCodec.codecForName("utf-8"))
Esempio n. 13
0
def load_ini(path, encoding='utf-8'):
    code = QTextCodec.codecForName(encoding)
    settings = QSettings(path, QSettings.IniFormat)
    settings.setIniCodec(code)

    return settings
Esempio n. 14
0
 def __init__(self, conf = "qt.conf", parent = None):
     QSettings.__init__(self, conf, QSettings.IniFormat, parent)
     self.setIniCodec(QTextCodec.codecForName("utf-8"))
Esempio n. 15
0
 def __init__(self, parent, readonly=False, enable_actions=True):
     super(DeenEncoderWidget, self).__init__(parent)
     self.ui = Ui_DeenEncoderWidget()
     self.ui.setupUi(self)
     self.parent = parent
     self.readonly = readonly
     self.current_pick = None
     self.current_combo = None
     self._content = bytearray()
     self.formatted_view = False
     self.codec = QTextCodec.codecForName('UTF-8')
     self.hex_view = False
     # Assign custom widgets for text_field and hex_field.
     # TODO: create proper widgets for text and hex widget.
     self.text_field = TextViewWidget(self, readonly=self.readonly)
     self.text_field.textChanged.connect(self.field_content_changed)
     self.hex_field = HexViewWidget(read_only=self.readonly, parent=self)
     self.hex_field.setHidden(True)
     self.hex_field.bytesChanged.connect(self.field_content_changed)
     self.ui.content_area_layout.addWidget(self.text_field)
     self.ui.content_area_layout.addWidget(self.hex_field)
     # Configure widget elements
     self.ui.toggle_text_view.setChecked(True)
     self.ui.toggle_text_view.toggled.connect(self.view_text)
     self.ui.toggle_hex_view.setChecked(False)
     self.ui.toggle_hex_view.toggled.connect(self.view_hex)
     # Set icons based on current theme darkness. Assume dark theme
     # if background color is below 50% brightness.
     if self.palette().color(self.backgroundRole()).value() < 128:
         self.ui.clear_button.setIcon(
             QIcon(MEDIA_PATH + 'dark/edit-clear.svg'))
         self.ui.save_button.setIcon(
             QIcon(MEDIA_PATH + 'dark/document-save-as.svg'))
         self.ui.copy_to_clipboard_button.setIcon(
             QIcon(MEDIA_PATH + 'dark/edit-copy.svg'))
         self.ui.move_to_root_button.setIcon(
             QIcon(MEDIA_PATH + 'dark/go-up.svg'))
     else:
         self.ui.clear_button.setIcon(QIcon(MEDIA_PATH + 'edit-clear.svg'))
         self.ui.save_button.setIcon(
             QIcon(MEDIA_PATH + 'document-save-as.svg'))
         self.ui.copy_to_clipboard_button.setIcon(
             QIcon(MEDIA_PATH + 'edit-copy.svg'))
         self.ui.move_to_root_button.setIcon(QIcon(MEDIA_PATH +
                                                   'go-up.svg'))
     # Add connections for the encoder buttons.
     self.ui.clear_button.clicked.connect(self.clear_content)
     self.ui.save_button.clicked.connect(self.save_content)
     self.ui.copy_to_clipboard_button.clicked.connect(
         self.copy_to_clipboard)
     self.ui.move_to_root_button.clicked.connect(self.move_content_to_root)
     self.ui.hide_side_menu.clicked.connect(
         self.toggle_side_menu_visibility)
     self.ui.hide_search_box.clicked.connect(
         self.toggle_search_box_visibility)
     # Update labels with proper values
     self.update_length_field(self)
     self.update_readonly_field(self)
     # The root widget will not have a plugin label and no "Move to root" button.
     self.ui.current_plugin_label.hide()
     if not self.readonly:
         self.ui.move_to_root_button.hide()
     # Disable the first element in all combo boxes.
     for combo in [
             self.ui.encode_combo, self.ui.decode_combo,
             self.ui.uncompress_combo, self.ui.compress_combo,
             self.ui.hash_combo, self.ui.misc_combo, self.ui.format_combo
     ]:
         combo.model().item(0).setEnabled(False)
     # Add all alvailable plugins to the corresponding combo boxes.
     for encoding in [
             p[1].display_name for p in self.parent.plugins.codecs
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.encode_combo.addItem(encoding)
     for encoding in [
             p[1].display_name for p in self.parent.plugins.codecs
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.decode_combo.addItem(encoding)
     for compression in [
             p[1].display_name for p in self.parent.plugins.compressions
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.compress_combo.addItem(compression)
     for compression in [
             p[1].display_name for p in self.parent.plugins.compressions
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.uncompress_combo.addItem(compression)
     for hash in [
             p[1].display_name for p in self.parent.plugins.hashs
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.hash_combo.addItem(hash)
     for misc in [
             p[1].display_name for p in self.parent.plugins.misc
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.misc_combo.addItem(misc)
     for formatter in [
             p[1].display_name for p in self.parent.plugins.formatters
             if (not getattr(p[1], 'cmd_only', None) or (
                 getattr(p[1], 'cmd_only', None) and not p[1].cmd_only))
     ]:
         self.ui.format_combo.addItem(formatter)
     # Add connections for combo boxes
     self.ui.encode_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.encode_combo))
     self.ui.decode_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.decode_combo))
     self.ui.compress_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.compress_combo))
     self.ui.uncompress_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.uncompress_combo))
     self.ui.hash_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.hash_combo))
     self.ui.misc_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.misc_combo))
     self.ui.format_combo.currentIndexChanged.connect(
         lambda: self.action(self.ui.format_combo))
     # Configure search widget
     self.ui.search_area.returnPressed.connect(self.search_highlight)
     self.ui.search_button.clicked.connect(self.search_highlight)
     self.ui.search_clear_button.clicked.connect(
         self.clear_search_highlight)
     self.ui.search_progress_bar.hide()
     self.error_message = QLabel()
     self.error_message.setStyleSheet('border: 2px solid red;')
     self.error_message.hide()
     self.ui.error_message_layout.addWidget(self.error_message)
     self.ui.error_message_layout_widget.hide()
     self.ui.search_group.hide()
     # After adding new widgets, we have to update the max scroll range.
     self.parent.ui.DeenMainWindow.verticalScrollBar().rangeChanged.connect(
         self.update_vertical_scroll_range)
     self.parent.ui.DeenMainWindow.horizontalScrollBar(
     ).rangeChanged.connect(self.update_horizontal_scroll_range)
Esempio n. 16
0
 def __init__(self, *args, **kwargs):
     super(Settings, self).__init__(*args, **kwargs)
     self.setDefaultFormat(self.IniFormat)
     self.setIniCodec(QTextCodec.codecForName("utf-8"))
Esempio n. 17
0
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
    if sys.platform != 'win32':
        app.setCursorFlashTime(0)

    #Set the codec for strings (QString)
    print("codec:", QTextCodec.codecForName('utf-8'))
    #QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8'))

    #Translator
    #qsettings = QSettings()
    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
    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)

        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)
    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_)
        if fileData:
            lineno = fileData[1]
            tempFiles.append((fileData[0], lineno))
    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_)
        lineno = fileData[1]
        tempFiles.append((fileData[0], lineno))
    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', '', type='QString')
    #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([(f[0], f[1] - 1) for f in zip(filenames, linenos)])
    file_without_nro = list([(f, 0) for f in 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()
    ide.show_python_detection()
    sys.exit(app.exec_())