예제 #1
0
    def accept(self):

        data = {}
        for t, (s, n) in zip(self.edit_tools, self.edit_info):
            data[s] = t.text()
            print(s)
        Settings.instance().setMulti(data, True)

        super(SettingsDialog, self).accept()
예제 #2
0
    def isMovie(path):
        dir,name = os.path.split(path)
        name,ext = os.path.splitext(name)

        exts = Settings.instance()["ext_movie"]

        return ext in exts
예제 #3
0
 def action_open_directory(self):
     # open the cwd in explorer
     cmdstr = Settings.instance()['cmd_open_native']
     path = self.view.pwd()
     print(cmdstr)
     print("--")
     os.system(cmdstr % path)
예제 #4
0
    def action_edit(self, item):

        path = self.view.realpath(item['name'])

        if self.view.isdir(path):
            pwd = path
        else:
            pwd, _ = self.view.split(path)

        if FileAssoc.isImage(path):
            cmdstr = Settings.instance()['cmd_edit_image']
            proc_exec(cmdstr % (path), pwd)
        else:  #if FileAssoc.isText(path):

            cmdstr = Settings.instance()['cmd_edit_text']
            proc_exec(cmdstr % (path), pwd)
예제 #5
0
    def reload(self):

        s = Settings.instance()
        self.key_playpause = s["keyhook_playpause"]
        self.key_stop = s["keyhook_stop"]
        self.key_next = s["keyhook_next"]
        self.key_prev = s["keyhook_prev"]
예제 #6
0
    def action_open(self, wf):

        path = wf.localPath
        # todo: get pwd, pass to proc_exec
        cmdstr = Settings.instance()['cmd_edit_text']

        proc_exec(cmdstr % (path))
예제 #7
0
    def initFileAssocTab(self):

        self.tab_assoc = Tab(self)
        self.tabview.addTab(self.tab_assoc, "File Association")
        self.assoc_grid = QGridLayout(self.tab_assoc)
        self.assoc_info = [("ext_text", "Text Files"),
                           ("ext_archive", "Archive Files"),
                           ("ext_image", "Image Files"),
                           ("ext_movie", "Video Files"),
                           ("ext_document", "Document Files")]
        self.assoc_tools = []

        for i, (s, n) in enumerate(self.assoc_info):
            print(i, s, n)
            edit = QLineEdit(self)
            terms = []
            for term in Settings.instance()[s]:
                if term.startswith("."):
                    term = term[1:]
                terms.append(term)
            terms_s = ', '.join(terms)
            edit.setText(terms_s)
            edit.setCursorPosition(0)
            lbl = QLabel(n + ":", self)
            lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.assoc_grid.addWidget(lbl, i, 0)
            self.assoc_grid.addWidget(edit, i, 1)
            self.assoc_tools.append(edit)
예제 #8
0
 def copy_remote_settings(self, dbpath, target_library):
     # if a remote database was copied locally, copy
     # the settings from that database to the new database
     # the next step will copy the new database back
     # to the target directory.
     #db_path = os.path.join(os.getcwd(),"remote.db")
     self.log("remote path: %s %s" % (dbpath, os.path.exists(dbpath)))
     if os.path.exists(dbpath):
         remote_sqlstore = SQLStore(dbpath)
         remote_settings = Settings(remote_sqlstore)
         remote_settings['_sync'] = 1  # token setting
         target_settings = Settings(target_library.sqlstore)
         for key, value in remote_settings.items():
             target_settings[key] = value
         remote_sqlstore.close()
         os.remove(dbpath)
예제 #9
0
    def isAudio(path):
        dir,name = os.path.split(path)
        name,ext = os.path.splitext(name)

        exts = Settings.instance()["ext_audio"]

        return ext in exts
예제 #10
0
 def generateData(self, songs=None):
     m = Settings.instance()['quicklist_minimum_song_count']
     if songs is None:
         songs = Library.instance().search("ban=0")
     text_transform = lambda x : [x,]
     if self.display_class == Song.genre:
         text_transform = lambda x : [ x.strip().title() for x in (x.replace(",",";").split(";")) if x.strip() ]
     data = buildQuickList(songs,self.display_class,text_transform,minimum=m)
     self.setData(data)
예제 #11
0
    def doTask(self):

        username = self.client.getUserName()
        if ":" in username:
            username, password = username.split(":")
            user = self.client.login(username, password)
            self.newApiKey.emit(username, user['apikey'])
            print(username)
            print(user['apikey'])

        lib = Library.instance().reopen()

        remote_songs = self.client.connect(callback=self._dlprogress)
        local_map = {s['uid']: s for s in lib.search(None)}

        for song in remote_songs:

            # match by id
            if song[Song.uid] in local_map:
                local_song = local_map[song[Song.uid]]
                del local_map[song[Song.uid]]
                song[Song.path] = local_song[Song.path]
                song[Song.remote] = SONG_SYNCED

            else:
                # not found locally
                song[Song.remote] = SONG_REMOTE
                # match by path
                # path = self.client.local_path(self.basedir, song)
                # if os.path.exists(path):
                #    song[Song.path] = path
                #    song[Song.remote] = SONG_SYNCED
                #    # self.addToDbIfMissing(lib, song)
                #    continue

        # songs not found on remote
        local_songs = list(local_map.values())
        for song in local_songs:
            song[Song.remote] = SONG_LOCAL

        songs = remote_songs + local_songs

        clss = {0: 0, 1: 0, 2: 0, 3: 0}
        for s in songs:
            clss[s[Song.remote]] += 1
        print(clss)

        self.setProgress(100)
        self.newLibrary.emit(songs)

        # success, update settings
        settings = Settings.instance().reopen()
        settings['remote_hostname'] = self.client.getHostName()
        settings['remote_username'] = self.client.getUserName()
        settings['remote_apikey'] = self.client.getApiKey()
        settings['remote_basedir'] = self.basedir
예제 #12
0
    def isText(path):
        dir,name = os.path.split(path)
        name,ext = os.path.splitext(name)

        if name.startswith(".") and ext =="":
            return True # dot file

        exts = Settings.instance()["ext_text"]

        return ext in exts
예제 #13
0
 def sync(self):
     pdialog = SyncProfileDialog(self)
     if pdialog.exec_():
         s = Settings.instance()
         dp = list(zip(s["playlist_preset_names"], s["playlist_presets"]))
         s = pdialog.export_settings()
         # feeling lazy right now, trusing no one will try to start
         # two sync dialogs at the same time.
         self.sdialog = SyncDialog(self.playlist_data, s, dp, self)
         self.sdialog.start()
         self.sdialog.show()
예제 #14
0
    def action_compare_2(self, model, items):

        lpath = model.view.realpath(items[0]['name'])
        rpath = model.view.realpath(items[1]['name'])

        cmdstr = Settings.instance()['cmd_diff_files']
        cmd = cmdstr % (lpath, rpath)
        args = shlex.split(cmd)
        print(args)
        subprocess.Popen(args)

        self.act_diff_left_path = None
예제 #15
0
    def _action_open_file_local(self, view, path):
        cmdstr_img = Settings.instance()['cmd_edit_image']

        if view.isdir(path):
            pwd = path
        else:
            pwd, _ = view.split(path)

        if isArchiveFile(path):
            self.openAsTab.emit(view, path)

        elif FileAssoc.isImage(path) and cmdstr_img:
            proc_exec(cmdstr_img % (path), pwd)
        elif FileAssoc.isText(path):
            cmdstr = Settings.instance()['cmd_edit_text']
            proc_exec(cmdstr % (path), pwd)
        elif FileAssoc.isAudio(path):
            cmdstr = Settings.instance()['cmd_play_audio']
            proc_exec(cmdstr % (path), pwd)
        elif FileAssoc.isMovie(path):
            cmdstr = Settings.instance()['cmd_play_video']
            proc_exec(cmdstr % (path), pwd)
        elif not fileIsBinary(view, path):
            cmdstr = Settings.instance()['cmd_edit_text']
            proc_exec(cmdstr % (path), pwd)
        else:
            cmdstr = Settings.instance()['cmd_open_native']
            proc_exec(cmdstr % (path), pwd)
예제 #16
0
    def onOpenRemote(self, tab, display, path):

        src = DirectorySource()
        view = display.view
        dtemp = src.join(Settings.instance()['database_directory'], "remote")
        src.mkdir(dtemp)

        remote_dname, remote_fname = view.split(path)
        ftemp = src.join(dtemp, remote_fname)

        with src.open(ftemp, "wb") as wb:
            view.getfo(path, wb)

        display._action_open_file_local(src, ftemp)

        self.wfctrl.addFile(ftemp, view, path)
예제 #17
0
    def showQuickMenu(self, event):
        pos = self.btn_quick.mapToGlobal(self.btn_quick.pos())

        menu = QMenu(self)

        d = Settings.instance().getMulti("playlist_preset_names",
                                         "playlist_presets")
        dp = list(zip(d["playlist_preset_names"], d["playlist_presets"]))

        for name, query in sorted(dp):
            menu.addAction(name).setData(query)

        action = menu.exec_(pos)

        if action is not None:
            self.run_search(action.data(), setText=True)
예제 #18
0
    def initEditTab(self):

        self.tab_edit = Tab(self)
        self.tabview.addTab(self.tab_edit, "Edit Tools")
        self.edit_grid = QGridLayout(self.tab_edit)

        self.edit_info = [("cmd_edit_text", "Text Editor"),
                          ("cmd_edit_image", "Image Editor"),
                          ("cmd_open_native", "Open Native"),
                          ("cmd_launch_terminal", "Open Terminal"),
                          ("cmd_diff_files", "Diff Tool"),
                          ("cmd_vagrant", "Vagrant Binary")]
        self.edit_tools = []
        for i, (s, n) in enumerate(self.edit_info):
            edit = QLineEdit(self)
            edit.setText(Settings.instance()[s])
            edit.setCursorPosition(0)
            lbl = QLabel(n + ":", self)
            lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.edit_grid.addWidget(lbl, i, 0)
            self.edit_grid.addWidget(edit, i, 1)
            self.edit_tools.append(edit)
예제 #19
0
    def onEnter(self):

        # delay creating the views until the tab is entered for the first
        # time, this slightly improves startup performance
        if self.ex_main.view is None:
            print("++ExplorerView onEnter", self.source.__class__.__name__)

            show_hidden = Settings.instance()['view_show_hidden']
            view1 = LazySourceListView(self.source,
                                       self.source.root(),
                                       show_hidden=show_hidden)
            view2 = LazySourceListView(self.source,
                                       self.source.root(),
                                       show_hidden=show_hidden)

            view1.loadDirectory.connect(
                lambda: self.onLazyLoadDirectory(self.ex_main))
            view2.loadDirectory.connect(
                lambda: self.onLazyLoadDirectory(self.ex_secondary))

            self.ex_main.setView(view1)
            self.ex_secondary.setView(view2)

            print("--ExplorerView onEnter", self.source.__class__.__name__)
예제 #20
0
 def action_openas_native(self, item):
     return self.action_openas(Settings.instance()['cmd_open_native'], item)
예제 #21
0
    def test_str(self):

        if os.path.exists(DB_PATH):
            os.remove(DB_PATH)

        sqlstore = SQLStore(DB_PATH)
        s = Settings(sqlstore)

        # -------------------------------------------------
        # test inserting/retrieving a string
        key = "strkey"
        val = "strval"
        s[key] = val
        self.assertEqual(s[key], val)

        # show that a string can be overwritten
        val = "foo"
        s[key] = val
        self.assertEqual(s[key], val)

        # can't overwrite an existing value with a different type
        with self.assertRaises(ValueError):
            s[key] = 123

        # -------------------------------------------------
        # test inserting/retrieving an integer
        key = "intkey"
        val = 1474
        s[key] = val
        self.assertEqual(s[key], val)

        # show that an integer can be overwritten
        val = 42
        s[key] = val
        self.assertEqual(s[key], val)

        # can't overwrite an existing value with a different type
        with self.assertRaises(ValueError):
            s[key] = "string"

        # -------------------------------------------------
        # test inserting/retrieving a list
        key = "csvkey"
        val = ["a", "b", "c"]
        s[key] = val
        self.assertEqual(s[key], val)

        # show that a list can be overwritten
        val = [
            "a",
        ]
        s[key] = val
        self.assertEqual(s[key], val)

        # can't overwrite an existing value with a different type
        with self.assertRaises(ValueError):
            s[key] = 123

        # -------------------------------------------------
        # setDefault only update if the key does not yet exist
        key = "default"
        val = "value"
        s.setDefault(key, val)
        self.assertEqual(s[key], val)
        s.setDefault(key, "new value")
        self.assertEqual(s[key], val)

        self.assertEqual(len(list(s.keys())), 4)
예제 #22
0
 def action_file(self, item):
     # TODO: remove
     # double click file action
     path = self.view.realpath(item['name'])
     cmdstr = Settings.instance()['cmd_open_native']
     os.system(cmdstr % path)
예제 #23
0
    def contextMenu(self, event, model, items):

        is_files = all(not item['isDir'] for item in items)
        is_dirs = all(item['isDir'] for item in items)

        ctxtmenu = QMenu(model)

        # file manipulation options
        menu = ctxtmenu.addMenu("New")
        menu.addAction("Empty File", lambda: model.action_touch_begin())
        menu.addAction("Folder", lambda: model.action_mkdir_begin())

        if len(items) > 0:
            menu = ctxtmenu.addMenu("Archive")
            menu.addAction("Add to 7z")
            menu.addAction("Add to zip")
            if len(items) == 1 and extract_supported(items[0]['name']):
                menu.addAction("Extract to *")
                menu.addAction("Extract to <named>")

        if len(items) == 1:
            # TODO: someday I should have a way to enable "default programs"
            # by file extension, and open alternatives
            # for now, there are only three classes I care about

            # todo:
            #   Open as ...
            #       Image (edit)  -- paint
            #       Image (view)  -- irfanview
            #       Internet      -- firefox
            # create a tab in the settings for managing context menus
            # the tab should be a table with the following values
            #   Name       -- displayed in the open as context menu
            #   executable -- path to program
            # possible option, each row in the table contains an ENUM value
            #   define Text, Audio, Vido, Image etc and the first defined
            #   of each type in the table iss considered "primary"
            #   and used by the model
            # possible option : finally implementing per extension
            #   handlers -- with some handlers that are "default" and always
            #   show for any extention, and another "default"  -- which
            #   is just open native for files with no known extension
            # this information should be stored in the database so that
            # the command line interface can access it
            menu = ctxtmenu.addMenu("Open As ...")
            menu.addAction("Text", lambda: model.action_edit(items[0]))
            menu.addAction("Audio",
                           lambda: model.action_openas_audio(items[0]))
            menu.addAction("Video",
                           lambda: model.action_openas_video(items[0]))
            menu.addAction("Native",
                           lambda: model.action_openas_native(items[0]))

            # add a menu option for opening the selected image in a
            # pop up window
            ext = model.view.splitext(items[0]['name'])[1]
            kind = ResourceManager.instance().getExtType(ext)
            if kind in (ResourceManager.IMAGE, ResourceManager.GIF):
                ctxtmenu.addAction("View Image",lambda : \
                    self.viewImage.emit(model.view, items[0]['name']))

        self._ctxtMenu_addFileOperations1(ctxtmenu, model, items)

        ctxtmenu.addSeparator()

        if model.view.islocal():
            if len(items) == 1:

                if not items[0]['isDir'] and items[0][
                        'isLink'] != DataSource.IS_LNK_BROKEN:
                    ctxtmenu.addAction("Edit",
                                       lambda: model.action_edit(items[0]))

                elif items[0]['isLink']:
                    ctxtmenu.addAction(
                        "Edit Link", lambda: model.action_edit_link(items[0]))

        ctxtmenu.addSeparator()

        if model.view.islocal() and Settings.instance()['cmd_diff_files']:
            ctxtmenu.addSeparator()

            if len(items) == 1:
                if self.act_diff_left_path is None:
                    ctxtmenu.addAction(
                        "Compare: Set Left",
                        lambda: self.action_compare_set_left(model, items[0]))
                else:
                    name = model.view.split(self.act_diff_left_path)[1]

                    ctxtmenu.addAction(
                        "Compare: Set Left",
                        lambda: self.action_compare_set_left(model, items[0]))
                    ctxtmenu.addAction(
                        "Compare to: %s" % name,
                        lambda: self.action_compare(model, items[0]))
            elif len(items) == 2:
                ctxtmenu.addAction("Compare 2 Items",
                                   lambda: self.action_compare_2(model, items))

        self._ctxtMenu_addFileOperations2(ctxtmenu, model, items)

        if model.view.islocal():
            ctxtmenu.addAction(QIcon(":/img/app_open.png"), "Open in Explorer",
                               model.action_open_directory)
            ctxtmenu.addAction("Open in Terminal", model.action_open_term)

        ctxtmenu.addAction("Refresh", model.action_refresh)

        action = ctxtmenu.exec_(event.globalPos())
예제 #24
0
def initSettings(path_base):

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

    settings_db_path = os.path.join(path_base,"settings.db")

    sqlstore = SQLStore(settings_db_path)
    Settings.init( sqlstore )

    Settings.instance()['database_directory']=path_base

    data = {}

    # basic associations by extension
    # TODO: pull the defaults out the resource manager,
    # settings menu can modify these (and update resource manager)
    fAssoc = ResourceManager.instance().getFileAssociation

    # TODO: resource manager doesnt keep track of text files, should it?
    data['ext_text'] = [".txt",".log",".md",]

    data['ext_archive']  = fAssoc(ResourceManager.ARCHIVE)
    data['ext_image']    = fAssoc(ResourceManager.IMAGE)
    data['ext_audio']    = fAssoc(ResourceManager.SONG);
    data['ext_movie']    = fAssoc(ResourceManager.MOVIE)
    data['ext_document'] = fAssoc(ResourceManager.DOCUMENT)
    data['ext_code']     = fAssoc(ResourceManager.CODE)

    if sys.platform == 'darwin':
        cmd_edit_text = "\"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl\" \"%s\""
        cmd_edit_image = ""
        cmd_open_native = "open \"%s\""
        cmd_launch_terminal = "open -b com.apple.terminal \"%s\""
        cmd_diff_files = "\"/Applications/Beyond Compare.app/Contents/MacOS/bcomp\" \"%s\" \"%s\""
        cmd_play_audio = "/Applications/VLC.app/Contents/MacOS/VLC \"%s\""
        cmd_play_video = "/Applications/VLC.app/Contents/MacOS/VLC \"%s\""
        cmd_vagrant = "vagrant"
    elif sys.platform=="win32":

        cmd_edit_text = "\"C:\\Program Files\\Sublime Text 3\\subl.exe\" \"%s\""
        #cmd_edit_image = "mspaint.exe \"%s\""
        cmd_edit_image = "pythonw \"D:\\Dropbox\\Code\\packages\\PyPaint\\PyPaint.py\" \"%s\""
        cmd_open_native = "explorer \"%s\""
        cmd_launch_terminal = "start /D \"%s\""
        cmd_diff_files = ""
        cmd_play_audio = ""
        cmd_play_video = ""
        cmd_vagrant = ""
    else:
        cmd_edit_text = "subl3 \"%s\""
        cmd_edit_image = ""
        # nemo caja thunar dolphin
        cmd_open_native = "nemo \"%s\""
        cmd_launch_terminal = "xterm -e \"cd %s; bash\""
        cmd_diff_files = ""
        cmd_play_audio = ""
        cmd_play_video = ""
        cmd_vagrant = ""

    data["cmd_edit_text"] = cmd_edit_text
    data["cmd_edit_image"] = cmd_edit_image
    data["cmd_open_native"] = cmd_open_native
    data["cmd_launch_terminal"] = cmd_launch_terminal
    data["cmd_diff_files"] = cmd_diff_files
    data["cmd_play_audio"] = cmd_play_audio
    data["cmd_play_video"] = cmd_play_video
    data["cmd_vagrant"] = cmd_vagrant

    # view_show_hidden is the default value for new tabs
    # each widget supports an individual setting, which can be toggled.
    data['view_show_hidden'] = True

    Settings.instance().setMulti(data,False)
예제 #25
0
def parse_args(script_file):

    procv = sys.argv[:]
    binpath = sys.argv[0]
    argv = sys.argv[1:]

    help_arg=""
    if len(argv)>0:
        help_arg = argv[0]
        if help_arg == "--bg" and len(argv)>1:
            help_arg = argv[1]
    if help_arg in ("-h","--help"):
        print_help(binpath);
        sys.exit(0)

    modes = get_modes()

    mode,xcut = "browse","-b"
    if len(argv)>0:
        for idx in range(len(argv)):
            opt = argv[idx]
            if opt in modes:
                # allows --edit or -e
                mode,xcut = modes[opt]
                procv.pop(idx+1)
                break;
            elif len(opt)>=2:
                # allows "-eh" for "edit help"
                if opt[:2] in modes:
                    mode,xcut = modes[opt[:2]]
                    new_opt = "-" + opt[2:]
                    if len(new_opt) == 1:
                        procv.pop(idx+1)
                    else:
                        procv[idx+1] = new_opt
                    break;
                elif opt[0]=="-" and opt[1]!="-": # illegal letter
                    print_help(binpath);
                    sys.exit(0)
    procv[0] = binpath + " " + xcut
    if binpath.endswith(".py"):
        procv[0] = sys.executable + " " + procv[0]

    parser = argparse.ArgumentParser(\
        description="Cross Platform File Explorer and FTP Browser")

    parser.add_argument("--pwd",dest="pwd",type=str,default=os.getcwd(),
                        help="working directory for relative paths given")

    if mode == "browse":
        parser.add_argument("--bg",dest="bg",action="store_true",
                            help="run gui as background task")
    else:
        if "--bg" in procv:
            procv.pop(procv.index("--bg"))

    if mode == "edit":
        parser.add_argument("-t","--touch",dest="touch",action="store_true",
                            help="create file if it does not exist")

    if mode == "compress":
        parser.add_argument("archive_path",type=str,nargs='?',
                        help="a secondary file or directory to display")
        parser.add_argument("path",type=str,nargs='+',
                        help="a secondary file or directory to display")
    elif mode == "extract":
        parser.add_argument("archive_path",type=str,
                        help="a secondary file or directory to display")
        parser.add_argument("directory",type=str,default=".",nargs="?",
                        help="directory to extract to. default is pwd")
    else:
        parser.add_argument("path",type=str,nargs='?', default = "",
                        help="a file or directory path to open")
        if mode in {"diff","browse"}:
            parser.add_argument("path_r",type=str,nargs='?',default="",
                            help="a secondary file or directory to display")

    pos_opts = []
    for p in parser._get_positional_actions():
        t = p.dest
        if p.default is not None:
            t = "[%s]"%t
        if p.nargs=="+":
            t = "%s..."%t
        pos_opts.append(t)
    pos_opts = " ".join(pos_opts)
    parser.usage="%s [options] %s"%(procv[0],pos_opts)
    args = parser.parse_args(procv[1:])

    if mode == "compress":
        sys.exit(do_compress(args))
    elif mode == "extract":

        sys.exit(do_extract(args))

    if mode not in {"diff","browse"}:
        args.path_r = None

    if args.path:
        args.path = os.path.expanduser(args.path)
        if not args.path.startswith("/"):
            args.path = os.path.join(args.pwd,args.path)

        if mode == "open":
            # open the file using user defined the OS native method
            cmdstr = Settings.instance()['cmd_open_native']
            cmdstr = cmdstr%args.path
            args=shlex.split(cmdstr)
            subprocess.Popen(args)
            sys.exit(0)

        if mode == "edit":
            #if mode == "edit" or FileAssoc.isText(args.path):

            # open the file for editing using the
            if not os.path.isfile(args.path):
                if args.touch:
                    open(args.path,"wb+").close()
                else:
                    sys.stderr.write("Error: Path not Found or not a File\n")
                    sys.stderr.write("%s\n"%args.path)
                    sys.exit(1)
            cmdstr = Settings.instance()['cmd_edit_text']
            cmdstr = cmdstr%(args.path)
            args=shlex.split(cmdstr)
            subprocess.Popen(args)
            sys.exit(0)

    else:
        args.path = args.pwd

    if args.path_r:
        args.path_r = os.path.expanduser(args.path_r)
        if not args.path_r.startswith("/"):
            args.path_r = os.path.join(args.pwd,args.path_r)

        if mode in {"browse",}:
            if os.path.isfile(args.path_r):
                #args.path_r,_ = os.path.split(args.path_r)
                print_help(binpath);
                sys.exit(1)

    if mode in {"browse",}:
        if os.path.isfile(args.path):
            print_help(binpath);
            sys.exit(1)

    if mode == "diff":
        cmdstr = Settings.instance()['cmd_diff_files']
        cmd=cmdstr%(args.path,args.path_r)
        args=shlex.split(cmd)
        subprocess.Popen(args)
        sys.exit(0)

    if args.bg:
        # user requested to run this process in the background
        # execute the process again, as a background task, then exit
        # (the double fork trick doesnt play nicely with Qt)
        # this wont work when frozen
        # detach stdout from the current shell

        argv=[sys.executable,script_file,"-b",args.path]
        if args.path_r:
            argv.append(args.path_r)
        environ=os.environ.copy()
        # TODO: this breaks windows
        envpath = sys.path + environ['PATH'].split(":")
        envset = set()
        envpath_unique = []
        for path in envpath:
            if path not in envset:
                envpath_unique.append(path)
                envset.add(path)
        environ['PATH']=':'.join(envpath_unique)
        print(environ['PATH'])
        subprocess.Popen(argv,cwd=os.getcwd(), \
                stderr= subprocess.DEVNULL,
                stdout= subprocess.DEVNULL,
                env = environ)
        sys.exit(0)

    return args
예제 #26
0
 def action_open_local_directory(self):
     # TODO !! local source
     ftemp = os.path.join(Settings.instance()['database_directory'],
                          "remote")
     self.changeDirectory.emit(ftemp)
예제 #27
0
    def __init__(self, parent=None):
        super(RemoteView, self).__init__(parent)

        self.client = None
        self.current_state = STATE_DISCONNECTED

        self.grid_info = QGridLayout()
        self.hbox_search = QHBoxLayout()
        self.hbox_admin = QHBoxLayout()
        self.vbox = QVBoxLayout(self)

        self.dashboard = Dashboard(self)

        self.edit_hostname = QLineEdit(self)
        self.edit_username = QLineEdit(self)
        self.edit_apikey = QLineEdit(self)
        self.edit_dir = QLineEdit(self)

        self.tbl_remote = RemoteTable(self)
        self.tbl_remote.showColumnHeader(True)
        self.tbl_remote.showRowHeader(False)

        self.edit_search = LineEdit_Search(self, self.tbl_remote,
                                           "Search Remote")

        self.btn_connect = QPushButton("Connect", self)

        lbl = QLabel("Hostname:")
        lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.grid_info.addWidget(lbl, 0, 0)
        self.grid_info.addWidget(self.edit_hostname, 0, 1)

        lbl = QLabel("User Name:")
        lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.grid_info.addWidget(lbl, 0, 2)
        self.grid_info.addWidget(self.edit_username, 0, 3)

        lbl = QLabel("Local Directory:")
        lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.grid_info.addWidget(lbl, 1, 0)
        self.grid_info.addWidget(self.edit_dir, 1, 1)

        lbl = QLabel("API Key:")
        lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.grid_info.addWidget(lbl, 1, 2)
        self.grid_info.addWidget(self.edit_apikey, 1, 3)

        self.lbl_error = QLabel("")
        self.lbl_search = QLabel("")

        self.cb_remote = QComboBox(self)
        self.cb_remote.addItem("Show All", SONG_ALL)
        self.cb_remote.addItem("Show Remote", SONG_REMOTE)  # index 1
        self.cb_remote.addItem("Show Local", SONG_LOCAL)  # index 2
        self.cb_remote.addItem("Show Sync", SONG_SYNCED)  # index 3
        self.cb_remote.currentIndexChanged.connect(self.onRemoteIndexChanged)

        self.btn_push = QPushButton("Push", self)
        self.btn_pull = QPushButton("Pull", self)
        self.btn_upload = QPushButton("Upload", self)
        self.btn_download = QPushButton("Download", self)
        self.chk_mode = QCheckBox("Master", self)
        self.chk_path = QCheckBox("Update Path", self)

        self.lbl_library = QLabel("Library:")
        self.lbl_library.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.lbl_history = QLabel("History:")
        self.lbl_history.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

        self.hbox_search.addWidget(self.btn_connect)
        self.hbox_search.addWidget(self.edit_search)
        self.hbox_search.addWidget(self.cb_remote)
        self.hbox_search.addWidget(self.lbl_search)

        self.hbox_admin.addWidget(self.chk_mode)
        self.hbox_admin.addWidget(self.chk_path)
        self.hbox_admin.addWidget(self.lbl_history)
        #self.hbox_admin.addWidget(self.btn_hardsync)
        #self.hbox_admin.addWidget(self.btn_hardpush)
        self.hbox_admin.addWidget(self.btn_push)
        self.hbox_admin.addWidget(self.btn_pull)
        #self.hbox_admin.addWidget(self.btn_delete)

        self.hbox_admin.addWidget(self.lbl_library)
        #self.hbox_admin.addWidget(self.btn_hardsync)
        #self.hbox_admin.addWidget(self.btn_hardpush)
        self.hbox_admin.addWidget(self.btn_upload)
        self.hbox_admin.addWidget(self.btn_download)
        #self.hbox_admin.addWidget(self.btn_delete)

        self.vbox.addLayout(self.grid_info)
        self.vbox.addLayout(self.hbox_admin)
        self.vbox.addLayout(self.hbox_search)
        self.vbox.addWidget(self.lbl_error)
        self.vbox.addWidget(self.tbl_remote.container)
        self.vbox.addWidget(self.dashboard)

        self.edit_hostname.setText(Settings.instance()['remote_hostname'])
        self.edit_username.setText(Settings.instance()['remote_username'])
        # "a10ddf873662f4aabd67f62c799ecfbb"
        self.edit_apikey.setText(Settings.instance()['remote_apikey'])
        self.edit_dir.setText(Settings.instance()['remote_basedir'])

        self.edit_search.textChanged.connect(self.onSearchTextChanged)
        self.btn_connect.clicked.connect(self.onConnectClicked)

        self.btn_pull.clicked.connect(self.onHistoryPullClicked)
        self.btn_push.clicked.connect(self.onHistoryPushClicked)
        self.btn_upload.clicked.connect(self.onLibraryUploadClicked)
        self.btn_download.clicked.connect(self.onLibraryDownloadClicked)
        self.chk_mode.stateChanged.connect(self.onModeStateChanged)
        #self.btn_delete.clicked.connect(self.onHistoryDeleteClicked)
        #self.btn_hardsync.clicked.connect(self.onHistoryHardSyncClicked)
        #self.btn_hardpush.clicked.connect(self.onHistoryHardPushClicked)

        self.tbl_remote.update_data.connect(self.refresh)  # on sort...

        self.grammar = RemoteSongSearchGrammar()
        self.song_library = []
        """
        # generate simple library for testing purposes.
        songs = Library.instance().search("",limit=100)
        for song in songs:
            song['remote'] = SONG_REMOTE
        self.song_library = songs
        """
        self.setSongs(self.song_library)
        self.chk_mode.setChecked(Qt.Checked)
        self.hbox_admin.setEnabled(False)
        self.edit_search.setEnabled(False)
        self.cb_remote.setEnabled(False)
예제 #28
0
 def action_openas_video(self, item):
     return self.action_openas(Settings.instance()['cmd_play_video'], item)
예제 #29
0
    def action_open_term(self):

        cmdstr = Settings.instance()['cmd_launch_terminal']
        path = self.view.pwd()
        proc_exec(cmdstr % (path), path)
예제 #30
0
    def editSettings(self):

        cmdstr = Settings.instance()['cmd_edit_text']
        path = YmlSettings.instance().path()
        proc_exec(cmdstr % (path), os.getcwd())