Пример #1
0
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False):
    dir = QDir()
    dir.setPath(from_dir)

    from_dir += QDir.separator()
    to_dir += QDir.separator()

    if not os.path.exists(to_dir):
        os.makedirs(to_dir)

    for file_ in dir.entryList(QDir.Files):
        from_ = from_dir + file_
        to_ = to_dir + file_

        if os.path.exists(to_):
            if replace_on_conflict:
                if not QFile.remove(to):
                    return False
            else:
                continue

        if not QFile.copy(from_, to_):
            return False

    for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot):
        from_ = from_dir + dir_
        to_ = to_dir + dir_

        if not os.path.exists(to_):
            os.makedirs(to_)

        if not copy_dir_recursive(from_, to_, replace_on_conflict):
            return False

    return True
Пример #2
0
 def initUndoRedo(self):
     self.undoStack = QUndoStack()
     temp = QDir(os.path.join(QDir.tempPath(), "FlatSiteBuilder"))
     if temp.exists():
         temp.removeRecursively()
     temp.setPath(QDir.tempPath())
     temp.mkdir("FlatSiteBuilder")
Пример #3
0
 def onMapsDirectoryChanged(self):
     prefs = preferences.Preferences.instance()
     mapsDir = QDir(prefs.mapsDirectory())
     if (not mapsDir.exists()):
         mapsDir.setPath(QDir.currentPath())
     self.model().setRootPath(mapsDir.canonicalPath())
     self.setRootIndex(self.model().index(mapsDir.absolutePath()))
Пример #4
0
 def initUndoRedo(self):
     self.undoStack = QUndoStack()
     temp = QDir(QDir.tempPath() + "/AppBuilder")
     if temp.exists():
         temp.removeRecursively()
     temp.setPath(QDir.tempPath())
     temp.mkdir("AppBuilder")
Пример #5
0
   def on_btnDir_setPath_clicked(self):
      self.__showBtnInfo(self.sender())
      curDir=QDir.currentPath()
      lastDir=QDir(curDir)
      self.ui.textEdit.appendPlainText("选择目录之前,QDir所指目录是:"+lastDir.absolutePath())

      aDir=QFileDialog.getExistingDirectory(self,"选择一个目录",curDir,QFileDialog.ShowDirsOnly)
      if aDir=="":
         return

      lastDir.setPath(aDir)
      self.ui.textEdit.appendPlainText("\n选择目录之后,QDir所指目录是:"+lastDir.absolutePath()+"\n")
Пример #6
0
    def __init__(self, mainWindow, parent = None):
        super().__init__(parent)
        self.mMainWindow = mainWindow

        self.setRootIsDecorated(False)
        self.setHeaderHidden(True)
        self.setItemsExpandable(False)
        self.setUniformRowHeights(True)
        self.setDragEnabled(True)
        self.setDefaultDropAction(Qt.MoveAction)
        prefs = preferences.Preferences.instance()
        prefs.mapsDirectoryChanged.connect(self.onMapsDirectoryChanged)
        mapsDir = QDir(prefs.mapsDirectory())
        if (not mapsDir.exists()):
            mapsDir.setPath(QDir.currentPath())
        self.mFSModel = FileSystemModel(self)
        self.mFSModel.setRootPath(mapsDir.absolutePath())

        nameFilters = QStringList("*.tmx")
        # The file system model name filters are plain, whereas the plugins expose
        # a filter as part of the file description
        filterFinder = QRegExp("\\((\\*\\.[^\\)\\s]*)")
        for format in PluginManager.objects(MapFormat):
            if not (format.capabilities() & MapFormat.Read):
                continue

            filter = format.nameFilter()
            if (filterFinder.indexIn(filter) != -1):
                nameFilters.append(filterFinder.cap(1))

        self.mFSModel.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDot)
        self.mFSModel.setNameFilters(nameFilters)
        self.mFSModel.setNameFilterDisables(False) # hide filtered files
        self.setModel(self.mFSModel)
        headerView = self.header()
        headerView.hideSection(1) # Size column
        headerView.hideSection(2)
        headerView.hideSection(3)
        self.setRootIndex(self.mFSModel.index(mapsDir.absolutePath()))
        self.header().setStretchLastSection(False)
        self.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.activated.connect(self.onActivated)

        self.mMainWindow = None
        self.mFSModel = None
Пример #7
0
    def saveDirectory(self, dirName):
        """
        Public method to save the search engine definitions to files.
        
        @param dirName name of the directory to write the files to (string)
        """
        dir = QDir()
        if not dir.mkpath(dirName):
            return
        dir.setPath(dirName)

        from .OpenSearchWriter import OpenSearchWriter
        writer = OpenSearchWriter()

        for engine in list(self.__engines.values()):
            name = self.generateEngineFileName(engine.name())
            fileName = dir.filePath(name)

            file = QFile(fileName)
            if not file.open(QIODevice.WriteOnly):
                continue

            writer.write(file, engine)
Пример #8
0
 def saveDirectory(self, dirName):
     """
     Public method to save the search engine definitions to files.
     
     @param dirName name of the directory to write the files to (string)
     """
     dir = QDir()
     if not dir.mkpath(dirName):
         return
     dir.setPath(dirName)
     
     from .OpenSearchWriter import OpenSearchWriter
     writer = OpenSearchWriter()
     
     for engine in list(self.__engines.values()):
         name = self.generateEngineFileName(engine.name())
         fileName = dir.filePath(name)
         
         file = QFile(fileName)
         if not file.open(QIODevice.WriteOnly):
             continue
         
         writer.write(file, engine)
Пример #9
0
def copy_dir_recursive(from_dir, to_dir, replace_on_conflict=False):
    dir = QDir()
    dir.setPath(from_dir)

    from_dir += QDir.separator()
    to_dir += QDir.separator()

    if not os.path.exists(to_dir):
        os.makedirs(to_dir)

    for file_ in dir.entryList(QDir.Files):
        from_ = from_dir + file_
        to_ = to_dir + file_
        if str(to_).endswith(".src"):
            to_ = str(to_).replace(".src", "")

        if os.path.exists(to_):
            if replace_on_conflict:
                if not QFile.remove(to_):
                    return False
            else:
                continue

        if not QFile.copy(from_, to_):
            return False

    for dir_ in dir.entryList(QDir.Dirs | QDir.NoDotAndDotDot):
        from_ = from_dir + dir_
        to_ = to_dir + dir_

        if not os.path.exists(to_):
            os.makedirs(to_)

        if not copy_dir_recursive(from_, to_, replace_on_conflict):
            return False

    return True
Пример #10
0
 def initUI(self):
     self.setWindowTitle("userFirefox - userChrome tweak manager")
     self.setGeometry(300, 300, 640, 640)
     self.layoutBox = LayoutBox()
     self.setLayout(self.layoutBox)
     currentDir = QDir().current()
     logging.info("Current application dir: %s", currentDir.path())
     currentDir.setFilter(
         QDir.Filters(24577)
     )  #filter only dirs 0x001 and no dots 0x2000 and 0x4000 results to 0d24577
     tweakCats = currentDir.entryList()
     tweaksAvail = {}
     tweaksTree = {}
     logging.debug("List of tweak categoriess: %s", tweakCats)
     for tCat in tweakCats:
         categoryDir = QDir()
         categoryDir.setPath(currentDir.path())
         categoryDir.cd(tCat)
         categoryDir.setFilter(
             QDir.Filters(2))  #filter files 0x002 results to 0d2
         logging.debug("Tweaks in category %s are %s", tCat,
                       categoryDir.entryList())
         tweaksAvail[tCat] = categoryDir.entryList()
     logging.info("Dictionary of all available tweaks: %s", tweaksAvail)
     for tCat in tweaksAvail:
         logging.debug(tCat)
         tweaksTree["_uFFTree"] = {}
         tweaksTree[tCat] = QTreeWidgetItem(
             self.layoutBox.filesBox.availableTweaks)
         tweaksTree[tCat].setText(0, tCat)
         for tName in tweaksAvail[tCat]:
             tweaksTree["_uFFTree"][tName] = QTreeWidgetItem(
                 tweaksTree[tCat])
             tweaksTree["_uFFTree"][tName].setText(0, tName)
     #qtreetop = QTreeWidgetItem(self.layoutBox.filesBox.availableTweaks)
     #qtreetop.setText(0, "baf")
     self.show()
Пример #11
0
class LayoutBox(QVBoxLayout):
    def __init__(self):
        super().__init__()
        self.profileGroup = QGroupBox("Profile")
        self.profileLabel = QLabel("none")
        self.profileSelect = QPushButton("Open...")
        self.profileSelect.clicked.connect(self.openProfileClick)
        self.profileSave = QPushButton("Save")
        self.profileSave.clicked.connect(self.saveProfileClick)
        self.profileSave.setEnabled(False)
        self.profileBox = QHBoxLayout()
        self.profileBox.addWidget(self.profileLabel)
        self.profileBox.addStretch()
        self.profileBox.addWidget(self.profileSelect)
        self.profileBox.addWidget(self.profileSave)
        self.profileGroup.setLayout(self.profileBox)

        self.filesBox = FilesBox()
        self.filesBox.buttonBox.setEnable(False)  #
        self.filesBox.availableTweaks.setEnabled(False)  #
        self.filesBox.selectedTweaks.setEnabled(False)  #

        self.filesBox.availableTweaks.itemClicked.connect(self.availClick)
        self.filesBox.selectedTweaks.itemClicked.connect(self.selectClick)

        self.descriptionGroup = QGroupBox("Tweak description")
        self.descriptionGroup.setMinimumHeight(50)
        self.description = QLabel("")
        self.description.setTextInteractionFlags(Qt.TextInteractionFlags(5))

        self.descriptionBox = QHBoxLayout()
        self.descriptionBox.addWidget(self.description)
        self.descriptionGroup.setLayout(self.descriptionBox)

        self.addWidget(self.profileGroup)
        self.addItem(self.filesBox)
        self.addWidget(self.descriptionGroup)
        self.profileDir = QDir()
        self.profilePathDialog = QFileDialog()
        self.profilePath = ""
        self.appDir = QDir().current()

    def openProfileClick(self):
        #Button Open... click
        self.profilePath = self.profilePathDialog.getExistingDirectory(
            self.profileSelect, "Select Firefox profile")
        # self.profilePath = "~/Library/Application Support/Firefox/Profiles/rpk2uobe.default"
        logging.debug("Selected directory: \"%s\"", self.profilePath)
        if self.profilePath != "":
            self.selectedProfile = QDir(self.profilePath)
            self.firefoxDir = QDir(self.profilePath)
            logging.debug("Selected profile qdir: %s",
                          self.selectedProfile.path())
            self.firefoxDir.cdUp()
            self.profilesFile = QFile(self.firefoxDir.path() + "/profiles.ini")
            logging.debug("Profiles file: %s", self.profilesFile.fileName())
            logging.debug("Profiles file exists: %s",
                          self.profilesFile.exists())
            logging.debug("Firefox folder: %s", self.firefoxDir.dirName())
            # Basic check if parent directory is named 'firefox' and contains a file named 'profiles.ini'
            #if self.firefoxDir.dirName() == "firefox" and self.profilesFile.exists():
            if True:
                self.profilePath = self.profilePath
                self.profileLabel.setText(self.profilePath)

                self.filesBox.buttonBox.setEnable(True)
                self.filesBox.availableTweaks.setEnabled(True)
                self.filesBox.selectedTweaks.setEnabled(True)
                self.profileSave.setEnabled(True)

                self.profileDir.setPath(self.profilePath)
                logging.debug("Profile dirs: %s", self.profileDir.entryList())
                self.userChrome = QFile(
                    self.profilePath + "/chrome/userChrome.css")
                self.userFFSettings = QFile(
                    self.profilePath + "/chrome/userFirefox.json")
                logging.debug("userChrome exists: %s",
                              self.userChrome.exists())
                if self.userChrome.exists(
                ) and not self.userFFSettings.exists():
                    self.backupChrome = QMessageBox()
                    self.backupChrome.setIcon(QMessageBox.Question)
                    self.backupChrome.setText(
                        "userChrome.css file already exists in this profile. This may be overwritten. Do you want to make a backup?"
                    )
                    self.backupChrome.setStandardButtons(
                        QMessageBox.StandardButtons(81920))  #yes, no
                    self.backupChrome.exec()
                    logging.debug("Dialog result: %s",
                                  self.backupChrome.result())
                    if self.backupChrome.result() == 16384:  #yes
                        logging.debug("Backing up userChrome")
                        self.backupDone = QMessageBox()
                        self.backupFile = QFile(
                            self.profilePath + "/chrome/userChrome.css~")
                        logging.debug("Backup file: %s",
                                      self.backupFile.fileName())
                        logging.debug("Backup exists: %s",
                                      self.backupFile.exists())
                        if self.backupFile.exists():
                            logging.debug("Backup already exists")
                            self.backupDone.setIcon(QMessageBox.Warning)
                            self.backupDone.setText(
                                "Backup already exists. The file was NOT overwritten and new backup not made."
                            )
                        else:
                            if self.userChrome.copy(self.profilePath +
                                                    "/chrome/userChrome.css~"):
                                self.backupDone.setIcon(
                                    QMessageBox.Information)
                                self.backupDone.setText(
                                    "Backed up to 'userChrome.css~'")
                            else:
                                self.backupDone.setIcon(QMessageBox.Critical)
                                self.backupDone.setText("Backing up failed.")
                        self.backupDone.exec()
                    elif self.backupChrome.result() == 65536:  #no
                        logging.debug("Not backing up userChome")
                # Load existing settings
                try:
                    with open(self.profilePath + "/chrome/userFirefox.json"
                              ) as uFP:
                        savedTweaks = json.load(uFP)
                    logging.debug("Loaded json settings: %s", savedTweaks)
                    for loadedTweak in savedTweaks:
                        logging.debug(
                            "Loaded tweak. check: %i, category: %s, name: %s",
                            loadedTweak["Enabled"], loadedTweak["Category"],
                            loadedTweak["Name"])
                        tweakCat = loadedTweak["Category"]
                        tweakName = loadedTweak["Name"]
                        self.filesBox.tweaksAdded[
                            tweakCat + tweakName] = QTreeWidgetItem(
                                self.filesBox.selectedTweaks)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setCheckState(
                                                      0,
                                                      loadedTweak["Enabled"])
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      1, tweakCat)
                        self.filesBox.tweaksAdded[tweakCat
                                                  + tweakName].setText(
                                                      2, tweakName)
                except FileNotFoundError:
                    pass
                self.filesBox.resizeColumns()
            else:
                self.noProfile = QMessageBox()
                self.noProfile.setIcon(QMessageBox.Warning)
                self.noProfile.setText(
                    "The selected directory does not appear to be a valid Firefox profile. Profiles are usually located at '~/.mozilla/firefox/xxxx' and is most likely a hidden directory."
                )
                self.noProfile.exec()

    def availClick(self):
        if self.filesBox.availableTweaks.currentItem().parent() is not None:
            tweakName = self.filesBox.availableTweaks.currentItem().text(0)
            tweakCat = self.filesBox.availableTweaks.currentItem().parent(
            ).text(0)
            self.showDesc(tweakCat, tweakName)

    def selectClick(self):
        try:
            tweakName = self.filesBox.selectedTweaks.currentItem().text(2)
            tweakCat = self.filesBox.selectedTweaks.currentItem().text(1)
            self.showDesc(tweakCat, tweakName)
        except:
            pass

    def showDesc(self, category, name):
        logging.debug("Showing description for %s/%s: ", category, name)
        currentDir = QDir().current().path()
        tweakPath = currentDir + "/" + category + "/" + name
        logging.debug("Loading %s", tweakPath)
        tweakDesc = ""
        descLines = 0
        with open(tweakPath) as tweakContent:
            for line in tweakContent:
                if (re.search("^(\/\* ?)|( \* ?)|( \*\/)", line) is not None):
                    if len(line) > 3:
                        trimmedLine = line[3:]
                        tweakDesc += trimmedLine
                        descLines += 1
                else:
                    break
        logging.debug("Description: %s", tweakDesc)
        self.description.setText(tweakDesc)
        logging.debug("Desc lines: %i", descLines)

    def saveProfileClick(self):
        logging.debug("Saving profile")
        self.saveQuestion = QMessageBox()
        self.saveQuestion.setIcon(QMessageBox.Question)
        self.saveQuestion.setStandardButtons(
            QMessageBox.StandardButtons(81920))  #yes, no
        self.saveQuestion.setText(
            "Do you want to apply selected tweaks and overwrite userChrome?")
        self.saveQuestion.exec()
        self.saveCSS = ""
        if self.saveQuestion.result() == 16384:  #yes
            logging.debug("Saving userChrome")
            selTweaksNumber = self.filesBox.selectedTweaks.topLevelItemCount()
            savingTweaks = []
            for i in range(selTweaksNumber):
                currentSavingTweak = self.filesBox.selectedTweaks.topLevelItem(
                    i)
                currentSavingData = {}
                currentSavingData["Enabled"] = currentSavingTweak.checkState(0)
                currentSavingData["Category"] = currentSavingTweak.text(1)
                currentSavingData["Name"] = currentSavingTweak.text(2)
                logging.debug("Tweak cat %s, name %s, selected %s",
                              currentSavingData["Category"],
                              currentSavingData["Name"],
                              currentSavingData["Enabled"])
                savingTweaks.append(currentSavingData)
                if currentSavingData["Enabled"] == 2:
                    with open(self.appDir.path() + "/" +
                              currentSavingData["Category"] + "/" +
                              currentSavingData["Name"]) as twkFile:
                        self.saveCSS += twkFile.read() + "\n"
            logging.debug("Selected tweaks: %s", savingTweaks)
            with open(self.profilePath + "/chrome/userFirefox.json",
                      "w") as fp:
                json.dump(savingTweaks, fp)
            logging.debug("userChrome.css: %s", self.saveCSS)
            with open(self.profilePath + "/chrome/userChrome.css", "w") as fp:
                fp.write(self.saveCSS)
        elif self.saveQuestion.result() == 65536:  #no
            logging.debug("Not saving userChrome.")
Пример #12
0
 def createDirectory(self):
     path = self.model.filePath(self.rootIndex())
     directory = QDir()
     directory.setPath(path)
     directory.mkpath("New Folder")