def printPreview(self):
        """
		export to a temporary PDF file and open in the default pdf viewer

		Raises `NotImplemented` if print preview is not supported on this platform (yet?)
		"""
        pdf_file = NamedTemporaryFile(suffix='.pdf', delete=False)
        try:
            self.exportToPDF(pdf_file)
            """
			#this clever pure-python implementation is probably not as portable as letting Qt handle it
			#though I'm not sure

			#get appropriate "document opener" program for the platform
			if 'linux' in sys.platform:
				prog_name = 'xdg-open'
			elif sys.platform == 'darwin': #Mac OS X
				prog_name = 'open'
			elif sys.platform == 'win32': #64 bit windows is still "win32"
				prog_name = 'start'
			else:
				raise NotImplemented('Your Platform (%s) does not support the print preview feature,'\
					'Export to PDF instead, please report this error' % sys.platform)
			subprocess.check_call([prog_name, pdf_file.name])
			"""

            QDesktopServices.openUrl(QUrl.fromLocalFile(pdf_file.name))
        finally:
            pdf_file.close()
Example #2
0
	def link_click_handler(self, url):
		if url.path() == u'blank':
			if url.hasFragment():
				if url.fragment() == u'quit':
					QApplication.instance().quit()
		else:			
			QDesktopServices.openUrl(url)
Example #3
0
    def printFile(self):
        """Generates a PDF file with all sentences included in database."""
        pdfdlg = pdf_dlg.PDFDialog(self.preferences, self.workspace)
        if pdfdlg.exec_():
            # We need to change this, pass the marker
            # inside of the function you divide it - pattern!
            marker = self.preferences['marker']
            marker_beg = marker[:len(marker) / 2]
            marker_end = marker[len(marker) / 2:]

            pdf_writer.exportToPDF(
                self.preferences['pdf']['path'], self.preferences['title'],
                self.preferences['author'], self.preferences['description'],
                self.container, marker_beg, marker_end,
                self.preferences['where'], self.preferences['replace_by'],
                self.preferences['pdf']['margin_top'],
                self.preferences['pdf']['margin_bottom'],
                self.preferences['pdf']['margin_left'],
                self.preferences['pdf']['margin_right'],
                self.preferences['pdf']['font'],
                self.preferences['pdf']['size'],
                self.preferences['pdf']['mode'])
            try:
                if self.preferences['pdf']['auto_open']:
                    QDesktopServices.openUrl(
                        QUrl("file:///" + self.preferences['pdf']['path'],
                             QUrl.TolerantMode))
            except:
                pass
	def printPreview(self):
		"""
		export to a temporary PDF file and open in the default pdf viewer

		Raises `NotImplemented` if print preview is not supported on this platform (yet?)
		"""
		pdf_file = NamedTemporaryFile(suffix='.pdf',delete=False)
		try:
			self.exportToPDF(pdf_file)

			"""
			#this clever pure-python implementation is probably not as portable as letting Qt handle it
			#though I'm not sure

			#get appropriate "document opener" program for the platform
			if 'linux' in sys.platform:
				prog_name = 'xdg-open'
			elif sys.platform == 'darwin': #Mac OS X
				prog_name = 'open'
			elif sys.platform == 'win32': #64 bit windows is still "win32"
				prog_name = 'start'
			else:
				raise NotImplemented('Your Platform (%s) does not support the print preview feature,'\
					'Export to PDF instead, please report this error' % sys.platform)
			subprocess.check_call([prog_name, pdf_file.name])
			"""

			QDesktopServices.openUrl(QUrl.fromLocalFile(pdf_file.name))
		finally:
			pdf_file.close()
Example #5
0
 def www_view(self):
     """ 
     Context Menu Action.
     Opens the stream in a web page. 
     """
     if self.stream is not None:
         print "Opening %s in a web browser..." % self.stream
         QDesktopServices.openUrl(self.stream.url)
Example #6
0
 def email_note(self):
     body = self.page.mainFrame().toPlainText()[
         len(self.title):
     ].strip()
     url = QUrl("mailto:")
     url.addQueryItem("subject", self.title)
     url.addQueryItem("body", body)
     QDesktopServices.openUrl(url)
Example #7
0
 def show_about(self):
     msg = QMessageBox()
     msg.setIcon(QMessageBox.Question)
     msg.setText("SpyKING CIRCUS v%s" % circus.__version__)
     msg.setWindowTitle("About")
     msg.setInformativeText("Documentation can be found at\n"
                            "http://spyking-circus.rtfd.org\n"
                            "\n"
                            "Open a browser to see the online help?")
     msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
     msg.setDefaultButton(QMessageBox.No)
     answer = msg.exec_()
     if answer == QMessageBox.Yes:
         QDesktopServices.openUrl(QUrl("http://spyking-circus.rtfd.org"))
Example #8
0
def _get_hamster_dir():
    hamster_dir = QDesktopServices.storageLocation(
        QDesktopServices.DataLocation)
    if not os.path.exists(hamster_dir):
        os.makedirs(hamster_dir)
        #TODO catch exception
    return hamster_dir
Example #9
0
    def open_file(self, path=None):
        """Opens path, which can be None, the path to an inselect document or
        the path to an image file. If None, the user is prompted to select a
        file.

        * If a .inselect file, the file is opened
        * If an image file for which a .inselect document already exists, the
        .inselect file is opened
        * If a _thumbnail.jpg file corresponding to an existing .inselect file,
        the .inselect file is opened
        * If an image file, a new .inselect file is created and opened
        """
        debug_print(u'MainWindow.open_file [{0}]'.format(path))

        if not path:
            folder = QSettings().value(
                'working_directory',
                QDesktopServices.storageLocation(
                    QDesktopServices.DocumentsLocation))

            filter = u'Inselect documents (*{0});;Images ({1})'
            filter = filter.format(InselectDocument.EXTENSION,
                                   u' '.join(IMAGE_PATTERNS))
            path, selectedFilter = QtGui.QFileDialog.getOpenFileName(
                self, "Open", folder, filter)

        if path:
            # Will be None if user cancelled getOpenFileName
            if not self.close_document():
                # User does not want to close the existing document
                pass
            else:
                path = Path(path)

                if path.suffix in IMAGE_SUFFIXES:
                    # Compute the path to the inselect document (which may or
                    # may not already exist) of the image file
                    doc_of_image = path.name.replace(
                        InselectDocument.THUMBNAIL_SUFFIX, u'')
                    doc_of_image = path.parent / doc_of_image
                    doc_of_image = doc_of_image.with_suffix(
                        InselectDocument.EXTENSION)
                else:
                    doc_of_image = None

                if InselectDocument.EXTENSION == path.suffix:
                    # Open the .inselect document
                    debug_print('Opening inselect document [{0}]'.format(path))
                    self.open_document(path)
                elif doc_of_image and doc_of_image.is_file():
                    # An image file corresponding to an existing .inselect file
                    msg = u'Opening inselect document [{0}] of thumbnail [{1}]'
                    debug_print(msg.format(doc_of_image, path))
                    self.open_document(doc_of_image)
                elif path.suffix in IMAGE_SUFFIXES:
                    msg = u'Creating new inselect document for image [{0}]'
                    debug_print(msg.format(path))
                    self.new_document(path)
                else:
                    raise InselectError('Unknown file type [{0}]'.format(path))
Example #10
0
 def browseVideos(self):
     self.rootPath = QDesktopServices.storageLocation(
         QDesktopServices.MoviesLocation)
     self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot
                                    | QDir.AllDirs)
     self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
     self.setWindowTitle(self.tr("Videos"))
Example #11
0
 def get_config_path(cls):
     config_path = os.path.join(
         QDesktopServices.storageLocation(QDesktopServices.DataLocation),
         "qsh")
     if not os.path.exists(config_path):
         os.makedirs(config_path)
     return os.path.join(config_path, "config")
    def __init__(self):
        dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True)
        session_bus = dbus.SessionBus(dbus_main_loop)
        bus_name = dbus.service.BusName("com.mikeasoft.statusnet",
                                        bus=session_bus)
        dbus.service.Object.__init__(self,
                                     object_path="/synchronize",
                                     bus_name=bus_name)

        self.app = QCoreApplication(sys.argv)
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        self.client = gconf.client_get_default()
        self.api_path = self.client.get_string(
            '/apps/ControlPanel/Statusnet/api_path')
        self.latest = self.client.get_int(
            '/apps/ControlPanel/Statusnet/latest')
        self.eventService = EventFeedService('statusnet', 'StatusNet')
        self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback"
        self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback"
        if not self.api_path:
            return
        self.cacheDir = QDesktopServices.storageLocation(
            QDesktopServices.CacheLocation)
        if not os.path.exists(self.cacheDir):
            os.mkdir(self.cacheDir)
        sys.exit(self.app.exec_())
Example #13
0
 def __init__(self, window, *, parent=None):
     super().__init__(parent)
     self.printer = None
     self.user = Username.name()
     self.indexPath = QDesktopServices.storageLocation(
         QDesktopServices.DocumentsLocation)
     self.outputPath = self.importPath = self.indexPath
     self.model = Xix.Model.Model(self.user)
     self.startCount = 0
     self.workTime = 0
     self.entryPanel = None
     self.spellPanel = None
     self.viewAllPanel = None
     self.viewFilteredPanel = None
     self.replacePanel = None
     self.window = window
     self.helpForm = None
     self.saving = False
     self.editors = set()
     self.gotoEids = collections.deque(maxlen=MAX_DYNAMIC_ACTIONS)
     self.mode = ModeKind.NO_INDEX
     self.spell = True
     self.pagesCache = ""
     self.showMessageTime = 10000
     self.initializeDisplayFonts()
Example #14
0
    def __init__(self, app):
        super(MainWindow, self).__init__()

        # Window layout - a splitter with the image on the left and controls
        # on the right
        self._image_widget = ImageLabel(self)
        self._controls = Controls(self)
        self._splitter = QSplitter()
        self._splitter.addWidget(self._image_widget)
        self._splitter.addWidget(self._controls)
        self._splitter.setSizes([1200, 600])

        # Main window layout
        self.setCentralWidget(self._splitter)

        # Connect controls to handlers
        self._controls.ok.clicked.connect(self.ok)
        self._controls.cancel.clicked.connect(self.cancel)
        self._controls.inbox.choose_directory.clicked.connect(
            self.choose_inbox)
        self._controls.processed.choose_directory.clicked.connect(
            self.choose_processed)

        # Directories
        mydocuments = QDesktopServices.storageLocation(
            QDesktopServices.DocumentsLocation)
        self._inbox = Path(QSettings().value('inbox',
                                             str(Path(mydocuments) / 'inbox')))
        self._processed = Path(QSettings().value(
            'processed', str(Path(mydocuments) / 'processed')))

        self._controls.inbox.set_link(str(self._inbox.as_uri()),
                                      self._inbox.name)
        self._controls.processed.set_link(str(self._processed.as_uri()),
                                          self._processed.name)

        # A stack of Path objects to be processed
        self._pending_files = []

        # The Path currently shown in the UI
        self._under_review = None

        # Watch the inbox directory, if it exists
        self.new_pending_files.connect(self.process_next_pending,
                                       QtCore.Qt.QueuedConnection)

        if self._inbox.is_dir():
            self._watcher = NewFileWatcher(self._inbox, IMAGE_SUFFIXES_RE)
            self._watcher.new_file.connect(self.new_image_file)
        else:
            self._watcher = None

        self.empty_controls()

        # Setup drag-drop handling
        self.setAcceptDrops(True)
        self._controls.installEventFilter(self)
        self._splitter.installEventFilter(self)
Example #15
0
 def browseMediapath(self):
     self.loadMediaBrowseSettings()
     options = QtGui.QFileDialog.Options()
     if (os.path.isdir(self.mediadirectory)):
         defaultdirectory = self.mediadirectory
     elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))):
         defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
     elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))):
         defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
     else:
         defaultdirectory = ""
     browserfilter = "All Files (*)"       
     fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory,
             browserfilter, "", options)
     if fileName:
         self.mediapathTextbox.setText(fileName)
         self.mediadirectory = os.path.dirname(fileName)
         self.saveMediaBrowseSettings()
Example #16
0
 def askOpenFile(self):
     if not self.askSaveChanges():
         return
     directory = QDesktopServices.storageLocation(
         QDesktopServices.DocumentsLocation)
     filename, selected_filter = QFileDialog.getOpenFileName(
         self, self.trUtf8(b'Open file'), directory)
     if filename:
         self.load(filename)
Example #17
0
 def browseMediapath(self):
     self.loadMediaBrowseSettings()
     options = QtGui.QFileDialog.Options()
     if (os.path.isdir(self.mediadirectory)):
         defaultdirectory = self.mediadirectory
     elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))):
         defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
     elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))):
         defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
     else:
         defaultdirectory = ""
     browserfilter = "All files (*)"       
     fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory,
             browserfilter, "", options)
     if fileName:
         self.mediapathTextbox.setText(os.path.normpath(fileName))
         self.mediadirectory = os.path.dirname(fileName)
         self.saveMediaBrowseSettings()
Example #18
0
    def event_link_clicked(self, url):
        url_string = url.toString()

        if 'file' in urlparse.parse_qs(urlparse.urlparse(url_string).query):
            msgbox = QMessageBox()
            msgbox.setWindowTitle('Installing')
            msgbox.setText('Installing theme. Please wait...')
            msgbox.setStandardButtons(0)
            msgbox.setAttribute(Qt.WA_DeleteOnClose)
            msgbox.setWindowModality(Qt.NonModal)
            msgbox.show()
            msgbox.repaint(
            )  # Qt didn't want to show the text so we force a repaint

            # Download and install the theme
            package = self.module.download(
                'http://localhost/test/download.php?file=2800&name=Fat-flat.xpf'
            )
            #package = self.module.download(url_string)
            try:
                self.module.install(package)
                msgbox.close()

                complete_msgbox = QMessageBox()
                complete_msgbox.setWindowTitle('Complete')
                complete_msgbox.setText('Install complete.')
                complete_msgbox.setStandardButtons(QMessageBox.Ok)
                complete_msgbox.setAttribute(Qt.WA_DeleteOnClose)
                complete_msgbox.exec_()
            except:
                msgbox.close()
                print "Unexpected error:", sys.exc_info()[:2]

                failed_msgbox = QMessageBox()
                failed_msgbox.setWindowTitle('Failed')
                failed_msgbox.setText(
                    'Install failed. Please try again later.')
                failed_msgbox.setStandardButtons(QMessageBox.Ok)
                failed_msgbox.setAttribute(Qt.WA_DeleteOnClose)
                failed_msgbox.exec_()
        else:
            QDesktopServices.openUrl(url)
Example #19
0
    def __init__(self, app):
        super(MainWindow, self).__init__()

        # Window layout - a splitter with the image on the left and controls
        # on the right
        self._image_widget = ImageLabel(self)
        self._controls = Controls(self)
        self._splitter = QSplitter()
        self._splitter.addWidget(self._image_widget)
        self._splitter.addWidget(self._controls)
        self._splitter.setSizes([1200, 600])

        # Main window layout
        self.setCentralWidget(self._splitter)

        # Connect controls to handlers
        self._controls.ok.clicked.connect(self.ok)
        self._controls.cancel.clicked.connect(self.cancel)
        self._controls.inbox.choose_directory.clicked.connect(self.choose_inbox)
        self._controls.processed.choose_directory.clicked.connect(self.choose_processed)

        # Directories
        mydocuments = QDesktopServices.storageLocation(
            QDesktopServices.DocumentsLocation)
        self._inbox = Path(QSettings().value('inbox',
            str(Path(mydocuments) / 'inbox')))
        self._processed = Path(QSettings().value('processed',
            str(Path(mydocuments) / 'processed')))

        self._controls.inbox.set_link(str(self._inbox.as_uri()), self._inbox.name)
        self._controls.processed.set_link(str(self._processed.as_uri()), self._processed.name)

        # A stack of Path objects to be processed
        self._pending_files = []

        # The Path currently shown in the UI
        self._under_review = None

        # Watch the inbox directory, if it exists
        self.new_pending_files.connect(self.process_next_pending,
            QtCore.Qt.QueuedConnection)

        if self._inbox.is_dir():
            self._watcher = NewFileWatcher(self._inbox, IMAGE_SUFFIXES_RE)
            self._watcher.new_file.connect(self.new_image_file)
        else:
            self._watcher = None

        self.empty_controls()

        # Setup drag-drop handling
        self.setAcceptDrops(True)
        self._controls.installEventFilter(self)
        self._splitter.installEventFilter(self)
Example #20
0
 def askSaveFile(self):
     if self.currentFilename:
         directory = os.path.dirname(self.currentFilename)
     else:
         directory = QDesktopServices.storageLocation(
             QDesktopServices.DocumentsLocation)
     filename, selected_filter = QFileDialog.getSaveFileName(
         self, self.trUtf8(b'Save file'), directory)
     if not filename:
         return False
     return self.saveFile()
Example #21
0
 def create_params_file(self, fname):
     msg = QMessageBox()
     msg.setIcon(QMessageBox.Question)
     msg.setText("Parameter file %r not found, do you want SpyKING CIRCUS to "
                 "create it for you?" % fname)
     msg.setWindowTitle("Generate parameter file?")
     msg.setInformativeText("This will create a parameter file from a "
                            "template file and open it in your system's "
                            "standard text editor. Fill properly before "
                            "launching the code. See the documentation "
                            "for details")
     msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
     answer = msg.exec_()
     if answer == QMessageBox.Yes:
         user_path = os.path.join(os.path.expanduser('~'), 'spyking-circus')
         if os.path.exists(user_path + 'config.params'):
             config_file = os.path.abspath(user_path + 'config.params')
         else:
             config_file = os.path.abspath(
                 pkg_resources.resource_filename('circus', 'config.params'))
         shutil.copyfile(config_file, fname)
         QDesktopServices.openUrl(QUrl(fname))
Example #22
0
    def __init__(self):
        self.configpath = os.path.join(QDS.storageLocation(QDS.DataLocation),
                                       PROGRAM_NAME)
        self.configfile = os.path.join(self.configpath, "config.json")

        logger.debug("Loading configuration from: %s" % self.configfile)
        try:
            with open(self.configfile, 'r') as handle:
                self.values = json.load(handle)
            logger.debug("Configuration loaded")
        except:
            logger.error("Failed to load configuration file!")
            self.values = {}
Example #23
0
	def event_link_clicked(self, url):
		url_string = url.toString()

		if 'file' in urlparse.parse_qs(urlparse.urlparse(url_string).query):
			msgbox = QMessageBox()
			msgbox.setWindowTitle('Installing')
			msgbox.setText('Installing theme. Please wait...')
			msgbox.setStandardButtons(0)
			msgbox.setAttribute(Qt.WA_DeleteOnClose)
			msgbox.setWindowModality(Qt.NonModal)
			msgbox.show()
			msgbox.repaint() # Qt didn't want to show the text so we force a repaint

			# Download and install the theme
			package = self.module.download('http://localhost/test/download.php?file=2800&name=Fat-flat.xpf')
			#package = self.module.download(url_string)
			try:
				self.module.install(package)
				msgbox.close()

				complete_msgbox = QMessageBox()
				complete_msgbox.setWindowTitle('Complete')
				complete_msgbox.setText('Install complete.')
				complete_msgbox.setStandardButtons(QMessageBox.Ok)
				complete_msgbox.setAttribute(Qt.WA_DeleteOnClose)
				complete_msgbox.exec_()
			except:
				msgbox.close()
				print "Unexpected error:", sys.exc_info()[:2]

				failed_msgbox = QMessageBox()
				failed_msgbox.setWindowTitle('Failed')
				failed_msgbox.setText('Install failed. Please try again later.')
				failed_msgbox.setStandardButtons(QMessageBox.Ok)
				failed_msgbox.setAttribute(Qt.WA_DeleteOnClose)
				failed_msgbox.exec_()
		else:
			QDesktopServices.openUrl(url)
Example #24
0
    def __init__(self):
        self.configpath = os.path.join(QDS.storageLocation(QDS.DataLocation), "n9rpn")
        self.configfile = os.path.join(self.configpath, "config.json")

        logger.debug("Loading configuration from: %s" % self.configfile)
        try:
            with open(self.configfile, 'r') as handle:
                self.values = json.load(handle)
            logger.debug("Configuration loaded")
        except:
            logger.error("Failed to load configuration file!")
            self.values = {'stack': [],
                           'format': "%0.4f",
                           'grad': 0,
                           'statistics': [0, 0, 0, 0, 0, 0, ]}
Example #25
0
def appdata():
    """
    Return the path that application data should be stored in. This acts a bit
    special on Windows machines as Qt doesn't return the right path itself.
    """
    if os.name == "nt":
        path = os.getenv("APPDATA")
        app = QCoreApplication.instance()
        if app:
            if app.organizationName():
                path = os.path.join(path, app.organizationName())
            if app.applicationName():
                path = os.path.join(path, app.applicationName())
        return path

    return QDesktopServices.storageLocation(QDesktopServices.DataLocation)
Example #26
0
File: path.py Project: sl5net/a2
def appdata():
    """
    Return the path that application data should be stored in. This acts a bit
    special on Windows machines as Qt doesn't return the right path itself.
    """
    if os.name == 'nt':
        path = os.getenv('APPDATA')
        app = QCoreApplication.instance()
        if app:
            if app.organizationName():
                path = os.path.join(path, app.organizationName())
            if app.applicationName():
                path = os.path.join(path, app.applicationName())
        return path

    return QDesktopServices.storageLocation(QDesktopServices.DataLocation)
Example #27
0
    def _make_backup_of_existing_file(cls, original_file_path):
        # We ask Qt for a suitable directory on the platform for user data.
        # On Windows it will resolve to something like:
        # C:\Users\<user_namer>\AppData\Local\python\qtlayoutbuilder\
        # Each file is timestamped like this:
        # archived_input-20170417-003554.txt

        dir_for_archive_copy = path.join(
            QDesktopServices.storageLocation(QDesktopServices.DataLocation),
            'qtlayoutbuilder')
        if not os.path.exists(dir_for_archive_copy):
            os.makedirs(dir_for_archive_copy)
        timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
        archive_fname = path.join(dir_for_archive_copy,
                                  'archived_input-' + timestamp + '.txt')
        shutil.copyfile(original_file_path, archive_fname)
        return dir_for_archive_copy, archive_fname
    def _on_export(self):
        if len(self.test.array) == 0:
            QMessageBox.warning(self, self.tr("IrregularVerbsTestGenerator"),
                                self.tr("You need to generate a test first !"))
            return

        export_file, export_format = QFileDialog.getSaveFileName(
            self, 
            self.tr("Save test"),
            QDesktopServices.storageLocation(QDesktopServices.DesktopLocation),
            self.tr("Xls file (*.xls)"))
        
        if not export_file:
            return

        include_solutions = self.mIncludeSolutions.isChecked()
        export_file = "{0}.xls".format(os.path.splitext(export_file)[0])
        _export_test_to_xls_file(self.test, export_file, include_solutions)
Example #29
0
def get_data_path():
    """
    Returns the path that application data should be stored in. This acts a bit
    special on Windows machines, using the APPDATA environment variable to
    ensure things go to AppData\Roaming and not AppData\Local.
    """
    if os.name == 'nt':
        qapp = QCoreApplication.instance()
        path = os.getenv('APPDATA')

        if qapp.organizationName():
            path = os.path.join(path, qapp.organizationName())

        if qapp.applicationName():
            path = os.path.join(path, qapp.applicationName())

        return path

    return QDesktopServices.storageLocation(QDesktopServices.DataLocation)
Example #30
0
File: profile.py Project: sl5net/a2
def get_data_path():
    """
    Returns the path that application data should be stored in. This acts a bit
    special on Windows machines, using the APPDATA environment variable to
    ensure things go to AppData\Roaming and not AppData\Local.
    """
    if os.name == 'nt':
        qapp = QCoreApplication.instance()
        path = os.getenv('APPDATA')

        if qapp.organizationName():
            path = os.path.join(path, qapp.organizationName())

        if qapp.applicationName():
            path = os.path.join(path, qapp.applicationName())

        return path

    return QDesktopServices.storageLocation(QDesktopServices.DataLocation)
Example #31
0
File: profile.py Project: sl5net/a2
def ensure_paths():
    """ Ensure cache_path, profile_path, and root_path are set. """
    global cache_path
    global profile_path
    global root_path

    if not root_path:
        root_path = os.path.abspath(os.path.dirname(sys.argv[0]))

    if not profile_path:
        # The profile path is a bit trickier than the root path, since it can
        # move depending on the portability flag.
        if portable:
            path = root_path
        else:
            path = os.path.abspath(get_data_path())

        # Add the Profiles/<profile> bit to the profile path, and ensure the
        # path actually exists.
        path = os.path.join(path, u'Profiles', name)
        if not os.path.exists(path):
            os.makedirs(path)

        profile_path = path

    if not cache_path:
        # The cache path is like the profile path, in that it varies based on
        # the portability flag.
        if portable:
            path = os.path.join(root_path, u'cache')
        else:
            path = QDesktopServices.storageLocation(
                QDesktopServices.CacheLocation)

        # Add the Profiles/<profile> bit to the cache path, and ensure the path
        # actually exists.
        path = os.path.join(path, u'Profiles', name)
        if not os.path.exists(path):
            os.makedirs(path)

        cache_path = path
Example #32
0
def ensure_paths():
    """ Ensure cache_path, profile_path, and root_path are set. """
    global cache_path
    global profile_path
    global root_path

    if not root_path:
        root_path = os.path.abspath(os.path.dirname(sys.argv[0]))

    if not profile_path:
        # The profile path is a bit trickier than the root path, since it can
        # move depending on the portability flag.
        if portable:
            path = root_path
        else:
            path = os.path.abspath(get_data_path())

        # Add the Profiles/<profile> bit to the profile path, and ensure the
        # path actually exists.
        path = os.path.join(path, u'Profiles', name)
        if not os.path.exists(path):
            os.makedirs(path)

        profile_path = path

    if not cache_path:
        # The cache path is like the profile path, in that it varies based on
        # the portability flag.
        if portable:
            path = os.path.join(root_path, u'cache')
        else:
            path = QDesktopServices.storageLocation(
                QDesktopServices.CacheLocation)

        # Add the Profiles/<profile> bit to the cache path, and ensure the path
        # actually exists.
        path = os.path.join(path, u'Profiles', name)
        if not os.path.exists(path):
            os.makedirs(path)

        cache_path = path
	def __init__(self):
		dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True)
		session_bus = dbus.SessionBus(dbus_main_loop)
		bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus)
		dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name)

		self.app = QCoreApplication(sys.argv)
		signal.signal(signal.SIGINT, signal.SIG_DFL)

		self.client = gconf.client_get_default()
		self.api_path = self.client.get_string('/apps/ControlPanel/Statusnet/api_path')
		self.latest = self.client.get_int('/apps/ControlPanel/Statusnet/latest')
		self.eventService = EventFeedService('statusnet', 'StatusNet')
		self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback"
		self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback"
		if not self.api_path:
			return
		self.cacheDir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
		if not os.path.exists(self.cacheDir):
			os.mkdir(self.cacheDir)
		sys.exit(self.app.exec_())
Example #34
0
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.test = Test()

        # Copy the default irv file into app data directory if necessary
        data_path = QDesktopServices.storageLocation(QDesktopServices.DataLocation)
        if not os.path.exists(data_path):
            os.makedirs(data_path)
        verbs_file_path = os.path.join(data_path, VERBS_FILE)
        if not os.path.exists(verbs_file_path):
            shutil.copy(os.path.join(QApplication.applicationDirPath(), VERBS_FILE), 
                        verbs_file_path)

        format_file_path = os.path.join(data_path, FORMAT_FILE)
        if not os.path.exists(format_file_path):
            shutil.copy(os.path.join(QApplication.applicationDirPath(), FORMAT_FILE), 
                        format_file_path)

        # Load verbs informations
        workbook = xlrd.open_workbook(verbs_file_path)
        self.levels_list = []
        self.levels_dict = {}
        for sheet in workbook.sheets():
            verbs = []
            for i in range(sheet.nrows):
                verb = Verb(sheet.row(i)[0].value, sheet.row(i)[1].value,
                            sheet.row(i)[2].value, sheet.row(i)[3].value)
                verbs.append(verb)
            self.levels_list.append(sheet.name)
            self.levels_dict[sheet.name] = Level(verbs)

        self.mClassList.currentIndexChanged.connect(self._on_level_selected_changed)
        for level in self.levels_list:
            self.mClassList.addItem(level, level)
        self.mGenerate.clicked.connect(self._on_generate)
        self.mExport.clicked.connect(self._on_export)
        self.mActionExport.triggered.connect(self._on_export)
        self.mActionEditVerbsList.triggered.connect(self._on_edit_verbs_list)
        self.mActionEditExportStyle.triggered.connect(self._on_edit_export_style)
Example #36
0
    def __init__(self, parent=None, flags=Qt.Widget):
        super(FileBrowser, self).__init__(parent, flags)

        self.gallery = QDocumentGallery(self)
        self.fileSystemModel = QFileSystemModel(self)

        self.rootPath = QDesktopServices.storageLocation(
            QDesktopServices.HomeLocation)
        self.fileSystemModel.setRootPath(self.rootPath)

        self.view = QListView()
        self.view.setModel(self.fileSystemModel)
        self.view.activated.connect(self.activated)

        self.setCentralWidget(self.view)

        self.menuBar().addAction(self.tr("Documents"), self.browseDocuments)
        self.menuBar().addAction(self.tr("Audio"), self.browseAudio)
        self.menuBar().addAction(self.tr("Images"), self.browseImages)
        self.menuBar().addAction(self.tr("Videos"), self.browseVideos)

        self.browseDocuments()
Example #37
0
    def addFiles(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, self.tr("Select Music Files"),
            QDesktopServices.storageLocation(QDesktopServices.MusicLocation),
            self.tr("Media Files (*.mp3 *.mp4 *.aac)")
        )
        if not files:
            return

        for mediafile in files:
            title = "unknown"
            artist, album, year = "", "", ""
            try:
                tag = EasyID3(mediafile)
                title = tag['title'][0]
                artist = tag['artist'][0]
                album = tag['album'][0]
                year = tag['date'][0]
            except:
                pass


            titleItem = QTableWidgetItem(title)
            titleItem.setFlags(titleItem.flags() ^ Qt.ItemIsEditable)
            artistItem = QTableWidgetItem(artist)
            artistItem.setFlags(artistItem.flags() ^ Qt.ItemIsEditable)
            albumItem = QTableWidgetItem(album)
            albumItem.setFlags(albumItem.flags() ^ Qt.ItemIsEditable)
            yearItem = QTableWidgetItem(year)
            yearItem.setFlags(yearItem.flags() ^ Qt.ItemIsEditable)

            currentRow = self.musicTable.rowCount()
            self.musicTable.insertRow(currentRow)
            self.musicTable.setItem(currentRow, 0, titleItem)
            self.musicTable.setItem(currentRow, 1, artistItem)
            self.musicTable.setItem(currentRow, 2, albumItem)
            self.musicTable.setItem(currentRow, 3, yearItem)
        self.engine.play_list_add(files)
        self.play_action()
Example #38
0
    def addFiles(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, self.tr("Select Music Files"),
            QDesktopServices.storageLocation(QDesktopServices.MusicLocation),
            self.tr("Media Files (*.mp3 *.mp4 *.aac)")
        )
        if not files:
            return

        for mediafile in files:
            title = "unknown"
            artist, album, year = "", "", ""
            try:
                tag = EasyID3(mediafile)
                title = tag['title'][0]
                artist = tag['artist'][0]
                album = tag['album'][0]
                year = tag['date'][0]
            except:
                pass


            titleItem = QTableWidgetItem(title)
            titleItem.setFlags(titleItem.flags() ^ Qt.ItemIsEditable)
            artistItem = QTableWidgetItem(artist)
            artistItem.setFlags(artistItem.flags() ^ Qt.ItemIsEditable)
            albumItem = QTableWidgetItem(album)
            albumItem.setFlags(albumItem.flags() ^ Qt.ItemIsEditable)
            yearItem = QTableWidgetItem(year)
            yearItem.setFlags(yearItem.flags() ^ Qt.ItemIsEditable)

            currentRow = self.musicTable.rowCount()
            self.musicTable.insertRow(currentRow)
            self.musicTable.setItem(currentRow, 0, titleItem)
            self.musicTable.setItem(currentRow, 1, artistItem)
            self.musicTable.setItem(currentRow, 2, albumItem)
            self.musicTable.setItem(currentRow, 3, yearItem)
        self.engine.play_list_add(files)
        self.play_action()
Example #39
0
 def acceptNavigationRequest(self, frame, request, type):
     modifiers = QApplication.keyboardModifiers()
     if modifiers == Qt.ControlModifier and type == QWebPage.NavigationTypeLinkClicked:
         QDesktopServices.openUrl(request.url())
     return False
Example #40
0
def open_external_urls(url):
    QDesktopServices.openUrl(url)
Example #41
0
File: path.py Project: sl5net/a2
def home():
    """ Return the path to the user's home directory. """
    return QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
 def on_pushButtonHelpOnline_clicked(self):
     QDesktopServices.openUrl(QUrl("http://desenvolvedoresdaruma.com.br/home/downloads/Site_2011/Help/DarumaFrameworkHelpOnline/Daruma_Framework.htm"))
Example #43
0
 def email_note(self):
     body = self.page.mainFrame().toPlainText()[len(self.title):].strip()
     url = QUrl("mailto:")
     url.addQueryItem("subject", self.title)
     url.addQueryItem("body", body)
     QDesktopServices.openUrl(url)
Example #44
0
 def on_open(self):
     if sys.platform.startswith('darwin'):
         url = '/Applications/Listen 1.app/Contents/MacOS/media/music/'
         QDesktopServices.openUrl(QUrl.fromLocalFile(url))
     else:
         QDesktopServices.openUrl(QUrl.fromLocalFile('./media/music'))
Example #45
0
    def on_start(self):
        self.myProcess = MyWorkerThread()
        self.myProcess.start()

        QDesktopServices.openUrl('http://localhost:8888/')
    def writeCSVReportForShotSelection(self,
                                       shotSelection=None,
                                       savePath=None):
        """Writes a csv file from a shotSelection, optionally saves tagged shots only. If running"""

        if not shotSelection:
            shotSelection = getSelectedShotsForActiveView()

        if len(shotSelection) <= 0:
            # If we're here we have no shots to work with - bail out.
            return

        sequence = shotSelection[0].parentSequence()
        tagDict = self.buildUniqueTagsDictFromShotSelection(shotSelection)

        if not savePath:
            currentTimeString = datetime.datetime.strftime(
                datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
            saveName = "TagReport_%s_%s.csv" % (sequence.name().replace(
                " ", "_"), currentTimeString)
            csvSavePath = os.path.join(os.getenv('HOME'), 'Desktop', saveName)
            savePath = openFileBrowser(caption="Save Tag Report .CSV as...",
                                       initialPath=csvSavePath,
                                       mayNotExist=True,
                                       forSave=True,
                                       pattern="*.csv")
            print "Save path %s" % savePath
            # A list is returned here, we SHOULD only get one file name, but force this to be only one, then check for .csv extension.
            if len(savePath) != 1:
                return
            else:
                savePath = savePath[0]

            if not savePath.lower().endswith(".csv"):
                savePath + ".csv"

        if len(savePath) == 0:
            return

        # The Header row for the CSV will contain some basic info re. the shot...
        sortedTagNames = sorted(tagDict)

        ### THIS HEADER MUST MATCH THE table_data line below ###
        csvHeader = [
            "Shot Name", "Duration", "Source Clip", "Track", "Type", "No. Tags"
        ]

        # Plus Tag names as columns
        if len(sortedTagNames) > 0:
            csvHeader.extend(sortedTagNames)

        # Get a CSV writer object
        csvFile = open(savePath, 'w')
        csvWriter = csv.writer(csvFile,
                               delimiter=',',
                               quotechar='|',
                               quoting=csv.QUOTE_MINIMAL)

        # Write the Header row to the CSV file
        csvWriter.writerow(csvHeader)

        for shot in shotSelection:
            currentTags = shot.tags()
            currentShotTagNames = [tag.name() for tag in currentTags]

            ### THIS LIST MUST MATCH THE csvHeader above ###
            table_data = [
                shot.name(),
                shot.duration(),
                shot.source().name(),
                shot.parentTrack().name(),
                shotMediaType(shot),
                str(len(currentTags))
            ]

            # Then add the remaining columns as TRUE/FALSE values in the tag columns
            for tag in sortedTagNames:
                if tag in currentShotTagNames:
                    table_data += ["TRUE"]
                else:
                    table_data += ["FALSE"]
            csvWriter.writerow(table_data)

        # Be good and close the file
        csvFile.close()
        print 'CSV Tag Report saved to: ' + str(savePath)

        # Conveniently show the CSV file in the native file browser...
        QDesktopServices.openUrl(
            QUrl('file:///%s' % (os.path.dirname(savePath))))
Example #47
0
 def openZipCodeTWAbout(self, *args, **kwargs):
     QDesktopServices.openUrl(QUrl('http://zipcode.mosky.tw/about'))
Example #48
0
 def on_donate_button_clicked(self):
     """Opens the donation link in a browser of the operating system."""
     QDesktopServices.openUrl(QUrl("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=TDQAJJ74TTYGJ", QUrl.StrictMode))
Example #49
0
def redirect_to_permission_page():
    QDesktopServices.openUrl(get_permission_url())
    quickstart(auth_server)
Example #50
0
File: path.py Project: sl5net/a2
def cache():
    """ Return a path for writing temporary files. """
    return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
Example #51
0
 def __init__(self):
   self.configpath = os.path.join(QDS.storageLocation(QDS.DataLocation),
     "GPS-Logger")
   self.configfile = self.configpath + "/" + self.configfile
   self.load()
Example #52
0
def get_home():
    """ Returns the path to the user's home directory. """
    return QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
Example #53
0
 def browseVideos(self):
     self.rootPath = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
     self.fileSystemModel.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs)
     self.view.setRootIndex(self.fileSystemModel.index(self.rootPath))
     self.setWindowTitle(self.tr("Videos"))
Example #54
0
  def writeCSVReportForShotSelection(self, shotSelection=None, savePath=None):
    """Writes a csv file from a shotSelection, optionally saves tagged shots only. If running"""

    if not shotSelection:
      shotSelection = getSelectedShotsForActiveView()

    if len(shotSelection) <= 0:
      # If we're here we have no shots to work with - bail out.
        return

    sequence = shotSelection[0].parentSequence()
    tagDict = self.buildUniqueTagsDictFromShotSelection(shotSelection)

    if not savePath:
      currentTimeString = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
      saveName = "TagReport_%s_%s.csv" % (sequence.name().replace(" ", "_"), currentTimeString)
      csvSavePath = os.path.join(os.getenv('HOME'), 'Desktop', saveName)
      savePath = openFileBrowser(caption="Save Tag Report .CSV as...", initialPath=csvSavePath, mayNotExist=True, forSave=True, pattern="*.csv")
      print "Save path %s" % savePath
      # A list is returned here, we SHOULD only get one file name, but force this to be only one, then check for .csv extension.
      if len(savePath)!=1:
        return
      else:
        savePath=savePath[0]

      if not savePath.lower().endswith(".csv"):
        savePath+".csv"

    if len(savePath)==0:
      return

    # The Header row for the CSV will contain some basic info re. the shot...
    sortedTagNames = sorted(tagDict)

    ### THIS HEADER MUST MATCH THE table_data line below ###
    csvHeader = ["Shot Name", "Duration", "Source Clip", "Track", "Type", "No. Tags"]

    # Plus Tag names as columns
    if len(sortedTagNames)>0:
      csvHeader.extend(sortedTagNames)

    # Get a CSV writer object
    csvFile = open(savePath, 'w')
    csvWriter = csv.writer( csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    # Write the Header row to the CSV file
    csvWriter.writerow(csvHeader)

    for shot in shotSelection:
      currentTags = shot.tags()
      currentShotTagNames = [tag.name() for tag in currentTags]

      ### THIS LIST MUST MATCH THE csvHeader above ###
      table_data = [shot.name(), 
                    shot.duration(), 
                    shot.source().name(), 
                    shot.parentTrack().name(), 
                    shotMediaType(shot),
                    str(len(currentTags))]

      # Then add the remaining columns as TRUE/FALSE values in the tag columns
      for tag in sortedTagNames:
        if tag in currentShotTagNames:
          table_data += ["TRUE"]
        else:
          table_data += ["FALSE"]
      csvWriter.writerow(table_data)

    # Be good and close the file
    csvFile.close()
    print 'CSV Tag Report saved to: ' + str(savePath)

    # Conveniently show the CSV file in the native file browser...
    QDesktopServices.openUrl(QUrl('file:///%s' % (os.path.dirname(savePath))))    
Example #55
0
def _get_hamster_dir():
    hamster_dir = QDesktopServices.storageLocation(QDesktopServices.DataLocation)
    if not os.path.exists(hamster_dir):
        os.makedirs(hamster_dir)
        #TODO catch exception
    return hamster_dir